提取:从提取响应中获取Cookie [英] fetch: Getting cookies from fetch response
问题描述
我正在尝试使用fetch on react实现客户端登录。
I'm trying to implement client login using fetch on react.
我正在使用护照进行身份验证。我使用 fetch
而不是常规的 form.submit()
的原因是因为我希望能够从我的快递服务器收到错误消息,例如:用户名或密码错误
。
I'm using passport for authentication. The reason I'm using fetch
and not regular form.submit()
, is because I want to be able to recieve error messages from my express server, like: "username or password is wrong"
.
我知道护照可以使用 flash
消息发送邮件,但使用 flash code>需要会话,我想避免使用它们。
I know that passport can send back messages using flash
messages, but flash
requires sessions and I would like to avoid them.
这是我的代码:
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的开发工具上看到的那样:
The server sends the cookies just fine, as you can see on chrome's dev tools:
但是Chrome不会在应用程序中设置Cookie -> Cookies->本地主机:8080:该站点没有cookie。
But chrome doesn't set the cookies, in Application -> Cookies -> localhost:8080: "The site has no cookies".
任何想法如何使其起作用?
Any idea how to make it work?
推荐答案
问题原来出在获取选项 credentials:same-origin / include
上。
由于fetch文档提到在请求上发送cookie时需要此选项,因此在读取cookie时未能提及。
The problem turned out to be with the fetch option credentials: same-origin/include
not being set.
As the fetch documentation mentions this option to be required for sending cookies on the request, it failed to mention this when reading a cookie.
所以我只是更改了我的代码是这样的:
So I just changed my code to be like this:
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 });
}
});
这篇关于提取:从提取响应中获取Cookie的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!