我已经尝试在我的应用程序中实现一些身份验证组件几个小时了,但我仍然不明白正在发生的一些事情。
基本上,我想发送 POST request
包含一些credentials
给我的API
,这会向我发送 cookie
如果凭据有效,则返回一个 token 。然后,该 cookie 应该包含在未来对我的 API 的所有请求的 header 中(我认为这是自动的)。
server.js(我的 API 目前是一个模型,带有 JSON 文件)
...
app.post('/api/login', jsonParser, (req, res) => {
fs.readFile(ACCOUNTS_FILE, (err, data) => {
if (err) {
console.error(err);
process.exit(1);
}
const accounts = JSON.parse(data);
const credentials = {
email: req.body.email,
password: req.body.password,
};
var token = null;
for (var i = 0; i < accounts.length; ++i) {
const account = accounts[i];
if (account.email === credentials.email
&& account.password === credentials.password) {
token = account.token;
break;
}
}
if (token) {
res.setHeader('Set-Cookie', `access_token=${token}; Secure; HttpOnly;`);
res.json({ token });
} else {
res.json({ token: null });
}
});
});
...
app.js
...
handleConnection(e) {
e.preventDefault();
const email = this.state.email.trim();
const password = this.state.password.trim();
if (!email && !password) {
return (false);
}
fetch(loginUrl, {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
credentials: 'include',
},
body: JSON.stringify(this.state),
})
.then((response) => response.json())
.then((data) => {
console.log(data);
})
.catch((error) => {
console.warn(error);
});
return (true);
}
...
现在是console.log(data)
总是显示我的 token (如果我的凭据错误则为 null),但 cookie 不起作用...
看,我收到 Set-Cookie
header,但我的页面上仍然没有 cookie。
即使我设法获取 cookie,当我尝试使用 document.cookie = "access_token=123";
创建 cookie 时然后再次发送请求,我的 cookie 不会像 jQuery Ajaxcall 那样进入我的 header :
我读到here添加 credentials: 'include'
本来可以挽救局面,但不幸的是它没有。
我在这里缺少什么?
提前致谢!
最佳答案
我遇到了同样的问题,我在 Peter Bengtsson 的评论中找到了答案:https://davidwalsh.name/fetch
如果我理解的话,在你的情况下,获取应该是:
fetch(loginUrl, {
credentials: 'same-origin',
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify(this.state),
})
关于cookies - 尝试使用react和fetch获取然后发送cookie,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36897364/