【发布时间】:2019-01-27 15:06:40
【问题描述】:
我在 expressJS 服务器和 VueJS 字体端之间的 cookie 身份验证方面遇到问题。
通过站点登录时,我成功在 set-cookie 标头中获得了一个 HTTPOnly Cookie: Screenshot (Ignore the Auth header, using it for testing only)
我也看到了cookie in the devTools,一切看起来都对我来说,虽然我不是 cookie 专家,所以它可能不正确
问题是当我在另一个端点上请求用户的设置时,cookie 没有发送到服务器。在服务器端处理此请求时,req.cookie 对象为空。
这是我的获取代码:
const loginOptions = {
method: 'POST',
mode: 'cors',
cache: 'no-cache',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
email: email,
password: password,
}),
credentials: 'same-origin',
};
const settingsOptions = {
method: 'GET',
mode: 'cors',
cache: 'no-cache',
headers: {
'Content-Type': 'application/json',
},
credentials: 'same-origin',
};
const loginResponse = await fetch(baseUrl + '/login', loginOptions);
const userSettings = await fetch(baseUrl + '/settings', settingsOptions);
我尝试过使用credentials: "include",但没有成功。
在快递服务器上,我正在使用这样的 cors:
app.use(cors({
origin: '*',
credentials: true,
}));
第二个请求的Here is also an example,403状态由服务器在没有附加cookie时设置。
我已尝试按照另一个线程中的建议将 cookie 的域设置为 localhost 和 127.0.0.1。 I have left it on localhost for now.
已解决
我在某处读到,您应该在创建 cookie 时为其添加特定的域值。如果我刚刚删除了该设置,我猜它会自动设置它,然后它就起作用了!所以我的猜测是我将域值设置为我尝试做的错误值
【问题讨论】:
-
baseUrl的值和调用fetch()的页面加载的URL是什么关系?如果 cookie 是为localhost:3000设置的,那么浏览器只会将它们发送到localhost:3000而不会发送到任何其他端口。 -
我认为您已经检查了开发工具中的第二个请求,以查看是否在请求标头中发送了 cookie
-
哦,也试试 firefox,只是为了排除其中一个答案中指出的 chrome 功能
-
baseUrl 的值为
localhost:3000,我从localhost:8080发送请求。是这个问题吗? -
关于Chrome的功能,我也试过firefox,可惜还是一样
标签: javascript node.js http cookies