我正在尝试使用fetch on react实现客户端登录。
我正在使用护照进行身份验证。我之所以使用fetch而不是普通的form.submit(),是因为我希望能够从我的express服务器接收错误消息,比如:"username or password is wrong"。
我知道flash可以使用flash消息发回消息,但passport需要会话,我希望避免使用它们。
这是我的代码:
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,在应用程序Cookies -> localhost:8080中:“网站没有cookies”。
你知道怎么让它工作吗?
发布于 2016-08-30 14:28:44
问题原来是未设置fetch选项credentials: same-origin/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 });
}
});发布于 2020-05-06 13:19:50
来自https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API的Difference与jQuery部分
发布于 2019-06-08 12:00:43
我花了很长时间,但没有一个对我有效。
在网上尝试了几个解决方案后,这个解决方案对我很有效。
希望它也能为你工作。
{
method: "POST",
headers: {
"content-type": "API-Key",
},
credentials: "include",
}https://stackoverflow.com/questions/39188376
复制相似问题