Ger*_*api 6 cookies fetch express
我正在尝试使用react上的fetch实现客户端登录。
我正在使用护照进行身份验证。我之所以使用fetch
而不是常规的原因form.submit()
是因为我希望能够从我的Express服务器接收错误消息,例如:"username or password is wrong"
。
我知道护照可以使用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 });
}
});
Run Code Online (Sandbox Code Playgroud)
服务器发送的cookie很好,如您在chrome的dev工具上看到的:
但是chrome不会设置cookie,在“应用程序”->“ cookies”->“ localhost:8080”中:“该站点没有cookie”。
任何想法如何使其工作?
问题原来是credentials: same-origin/include
没有设置fetch 选项。由于 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 });
}
});
Run Code Online (Sandbox Code Playgroud)
来自Mozilla 上 Fetch API的与 jQuery部分的差异:
\n