fetch 自动加cookie_尝试使用react和fetch获取然后发送cookie

博客作者在尝试实现应用中的身份验证组件时遇到了问题。他们发送POST请求到API并期望接收到的cookie能在后续请求中自动包含在头信息中。尽管API返回了Set-Cookie头,但浏览器并未保存cookie,且手动设置cookie后也无法在请求头中看到。解决方案是将fetch的credentials选项设置为'same-origin',这允许跨域请求携带cookie。
摘要由CSDN通过智能技术生成

I've been trying to implement some authentication component in my app for a few hours now, and I still don't understand some of the things that are happening.

Basically, I'd like to send a POST request containing some credentials to my API, which sends me a cookie back with a token if the credentials worked. Then, the cookie should be included in the headers of all future requests to my API (which I believed was automatic).

server.js (my API is a mockup for now, with JSON files)

...

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);

}

...

Now the console.log(data) always displays my token (or null if my credentials are wrong), but the cookie thing doesn't work...

See, I receive the Set-Cookie header, but I still have no cookie on my page.

And even if I managed to get the cookie, when I try to create a cookie using document.cookie = "access_token=123"; and then send the request again, my cookie doesn't go in my header like it would with a jQuery Ajaxcall :

I read here that adding credentials: 'include' would save the day, but unfortunately it didn't.

What am I missing here?

Thanks in advance!

解决方案

I had the same problem and I found the answer in Peter Bengtsson's comment here: https://davidwalsh.name/fetch

If I understood, in your case the fetch should be:

fetch(loginUrl, {

credentials: 'same-origin',

method: 'POST',

headers: {

Accept: 'application/json',

'Content-Type': 'application/json'

},

body: JSON.stringify(this.state),

})

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值