Express doesn't set a cookie Express doesn't set a cookie express express

Express doesn't set a cookie


I had the same issue. The server response comes with cookie set:

Set-Cookie:my_cookie=HelloWorld; Path=/; Expires=Wed, 15 Mar 2017 15:59:59 GMT 

But the cookie was not saved by a browser.

This is how I solved it.

I use fetch in a client-side code. If you do not specify credentials: 'include' in fetch options, cookies are neither sent to server nor saved by a browser, although the server response sets cookies.

Example:

var headers = new Headers();headers.append('Content-Type', 'application/json');headers.append('Accept', 'application/json');return fetch('/your/server_endpoint', {    method: 'POST',    mode: 'same-origin',    redirect: 'follow',    credentials: 'include', // Don't forget to specify this if you need cookies    headers: headers,    body: JSON.stringify({        first_name: 'John',        last_name: 'Doe'    })})

Hope it helps somebody.


Struggling with this for a 3h, and finally realized, with axios, I should set withCredentials to true, even though I am only receiving cookies.

axios.defaults.withCredentials = true;


i work with express 4 and node 7.4 and angular,I had the same problem me help this:
a) server side: in file app.js i give headers to all response like:

 app.use(function(req, res, next) {        res.header('Access-Control-Allow-Origin', req.headers.origin);      res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");      next(); });  

this must have before all router.
I saw a lot of added this headers:

res.header("Access-Control-Allow-Headers","*");res.header('Access-Control-Allow-Credentials', true);res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');

but i dont need that,

b) when you definer cookie you nee add httpOnly: false, like:

 res.cookie( key, value,{ maxAge: 1000 * 60 * 10, httpOnly: false });

c) client side: in send ajax you need add: "withCredentials: true," like:

$http({     method: 'POST',     url: 'url,      withCredentials: true,     data : {}   }).then(function(response){        // code     }, function (response) {         // code    });

good luck.