gpt4 book ai didi

express - fetch:从 fetch 响应中获取 cookie

转载 作者:行者123 更新时间:2023-12-04 15:31:49 30 4
gpt4 key购买 nike

我正在尝试使用 fetch on react 来实现客户端登录。

我正在使用护照进行身份验证。我使用的原因 fetch而不是常规 form.submit() , 是因为我希望能够从我的快速服务器接收错误消息,例如:"username or password is wrong" .

我知道护照可以使用 flash 发回消息消息,但 flash需要 session ,我想避免它们。

这是我的代码:

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 的开发工具上看到的那样:
Network - Cookies
Network - Headers

但是 chrome 没有设置 cookie,在 Application -> Cookies -> localhost:8080 中:“该站点没有 cookie”。

知道如何使它工作吗?

最佳答案

问题出在 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 });
}
});

关于express - fetch:从 fetch 响应中获取 cookie,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39188376/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com