Express.js 后端不将 cookie 保存到 Nuxt.js 前端

Express.js backend not saving cookie to Nuxt.js frontend

我用 Express.js 构建了一个授权服务器,它在使用 Postman 进行测试时可以工作,它将访问和轮换刷新令牌保存为签名 cookie。 但是,我完全忘记了,我的后端和前端是两个完全独立的服务器和域。我尝试启用 Access-Control-Allow-Credentials,但没有用。我没有收到任何错误消息,只是没有保存 cookie。

这是我的后端登录控制器:

const userLogin = async (req, res, next) => {
  const { email, password } = req.body;
  if (!email || !password) return res.sendStatus(400);

  try {
    const login = await loginUser(email, password);
    if (login == 'wrong_email_or_password') return res.status(200).json({ error: login });

    res.header('Access-Control-Allow-Credentials', true);

    res.cookie('access', login.accessToken, { httpOnly: true, secure: (env != 'dev'), signed: true });
    res.cookie('refresh', login.refreshToken, { httpOnly: true, secure: (env != 'dev'), signed: true });

    res.status(200).json(login);
  } catch(e) {
    console.log(e.message);
    res.sendStatus(500) && next();
  }
}

在我遇到一些 CORS 问题后,我也做了 app.use(cors({ origin: true, credentials: true }));,解决了这个问题。对于生产,我可能还会添加一个 CORS 白名单。

这是我的 Nuxt.js 方法,将在提交注册表单时调用:

async register () {
  try {
    if (!(this.firstname && this.lastname && this.username && this.email && this.password)) throw new Error('Pflichtfelder ausfüllen')

    const res = await axios.post(`${this.$axios.defaults.baseURL}register`, {
      firstname: this.firstname,
      lastname: this.lastname,
      username: this.username,
      email: this.email,
      password: this.password
    }, {
      withCredentials: true,
      credentials: 'include'
    })

    console.log(res)

    this.$router.go()
  } catch (e) {
    this.error = e.message
    console.error(e)
  }
}

我希望我能提供一些更有帮助的信息,而不是“不起作用,请帮忙”,但正如我所说,我没有收到任何错误,所以我真的不知道该去哪里看。 :(

好吧,看来我想做的事情是不可能的。来自 third-party 个域的 Cookie 是不允许的,现在我想起来是有道理的...

对于任何感兴趣的人,我的解决方案是将两个标记都保存在 localStorage 中。因为我使用的是旋转刷新令牌,所以这没什么大不了的。