Express 获取:从获取响应获取cookie
我正在尝试使用fetch on react实现客户端登录 我用passport认证。我之所以使用Express 获取:从获取响应获取cookie,express,cookies,fetch,Express,Cookies,Fetch,我正在尝试使用fetch on react实现客户端登录 我用passport认证。我之所以使用fetch而不是常规的form.submit(),是因为我希望能够接收来自express服务器的错误消息,例如:“用户名或密码错误” 我知道passport可以使用flash消息发送回消息,但flash需要会话,我希望避免使用会话 这是我的代码: fetch('/login/local', { method: 'POST', headers: { Accept:
fetch
而不是常规的form.submit()
,是因为我希望能够接收来自express服务器的错误消息,例如:“用户名或密码错误”
我知道passport可以使用flash
消息发送回消息,但flash
需要会话,我希望避免使用会话
这是我的代码:
fetch('/login/local', {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
username: this.state.username,
password: this.state.password,
}),
}).then(res => {
console.log(res.headers.get('set-cookie')); // undefined
console.log(document.cookie); // nope
return res.json();
}).then(json => {
if (json.success) {
this.setState({ error: '' });
this.context.router.push(json.redirect);
}
else {
this.setState({ error: json.error });
}
});
服务器发送cookie的方式很好,正如您在chrome的开发工具上看到的:
但是chrome没有设置cookies,在Application->cookies->localhost:8080:“站点没有cookies”
知道如何使其工作吗?问题在于没有设置获取选项
凭证:相同来源/include
。
由于fetch文档提到在请求时发送cookie需要此选项,因此在读取cookie时未提及此选项
所以我把代码改成这样:
fetch('/login/local', {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
credentials: 'same-origin',
body: JSON.stringify({
username: this.state.username,
password: this.state.password,
}),
}).then(res => {
return res.json();
}).then(json => {
if (json.success) {
this.setState({ error: '' });
this.context.router.push(json.redirect);
}
else {
this.setState({ error: json.error });
}
});
我花了很长时间,但什么都不管用 在网上尝试了几种解决方案后,这一种对我有效 希望它也能对你起作用
{
method: "POST",
headers: {
"content-type": "API-Key",
},
credentials: "include",
}
From与jQuery的差异
- fetch()将不会接收跨站点cookie。您无法建立跨站点cookie 使用fetch()的站点会话。来自其他站点的设置Cookie头是 默默地忽略李>
- fetch()不会发送cookies,除非您设置了 凭证初始化选项。自2017年8月25日起:规范更改了 同一来源的默认凭据策略。Firefox自 61.0b13。)