Set-Cookie 响应头不设置浏览器 cookie

问题描述 投票:0回答:1

我在用户登录后设置 cookie 时遇到问题。 (此问题仅在生产中出现)。 我的 /login 端点返回一个带有令牌和其他所需信息的 cookie(如下)

if (isPasswordValid === true) {
        jwt.sign({ username, id: userDoc._id }, secret, (error, token) => {
          if (error) throw error;
          res.cookie("token", token, { 
            httpOnly: true, 
            domain: "https://my-frontend-url.com",
            sameSite: "none",
            secure: true,
          }).status(200).json({
            message: "User have been logged in successfully",
            id: userDoc._id,
            username,
            authorname: userDoc.authorname,
          });
        });

然后我从客户端获取端点:

const res = await fetch(`${process.env.REACT_APP_API_URL}/login`, {
      method: "post",
      credentials: "include", 
      headers: {
        "content-type": "application/json",
      },
      body: JSON.stringify({
        username,
        password,
      }),
    });

在我获得 200 状态后,Set-Cookie 响应标头包含令牌,但它也有一个警告:“通过 Set-Cookie 标头设置 cookie 的尝试被阻止,因为其 Domain 属性对于当前而言无效主机网址。”

我也在使用cookie-parcer中间件:

app.use(cookieParser());
和cors middleare
app.use(cors({ credentials: true, origin: ["https://my-frontend-url.com", "http://localhost:3000"], }));
但仍然无法找出解决方案。

我尝试将

credentials: "include",
设置为获取请求。 我尝试使用cors:
app.use(cors({ credentials: true, origin: ["https://my-frontend-url.com", "http://localhost:3000"], }));
我也尝试过配置 res.cookie:
res.cookie("token", token, {  httpOnly: true,  domain: "https://my-frontend-url.com", sameSite: "none", secure: true, })
但这些都没有帮助。希望得到一些帮助,谢谢!

node.js express cookies setcookie
1个回答
0
投票

将域选项设置为

{ domain: ".my-frontend-url.com" }
© www.soinside.com 2019 - 2024. All rights reserved.