Response cookies not being set
See original GitHub issueI’m trying to implement client login using fetch on react.
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"
.
I know that passport can send back messages using flash
messages, but flash
requires sessions and I would like to avoid them.
This is my code:
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 });
}
});
The server sends the cookies just fine, as you can see on chrome’s dev tools:
But chrome doesn’t set the cookies, in Application -> Cookies -> localhost:8080: “The site has no cookies”.
Using form.submit()
while the server sets the cookies and redirects works just fine, the problem only occurs using fetch to retrieve json, so this is why I’m posting it here.
Any idea how to make it work?
Issue Analytics
- State:
- Created 7 years ago
- Comments:17
Wow. I just realized I did a major mistake.
So, I have two requests; one login request and one customer request. It is the login request that gets the set-cookie header in its response, and then the user should be loggen in.
There is an option called credentials: ‘same-origin’, which I did not send with the login request (because I thought it only needed to be sent with requests after I was logged in.)
Try this:
Make sure you don’t add the credentials: ‘same-origin’ in the header object. It is not supposed to be there. I’ve seen many do that mistake.
I had to use
credentials: 'include'
on the client side andCORS_ALLOW_CREDENTIALS = True
in my django app. Also setting my cookie with127.0.0.1
in localhostresponse.set_cookie('my_cookie', value=token, httponly=True, domain='127.0.0.1')