AleksW
AleksW

Reputation: 713

What am I doing wrong when trying to set a cookie using Express

I'm currently trying to send a cookie back to my react app after logging in, In my server I have a test response:

res.status(200).cookie('nameOfCookie', 'cookieValue', { maxAge: 1000* 60 * 60 }).end();

and in the app I have

Axios.post('http://localhost:5000/User/login', userDetails).then(res => {
    console.log(JSON.stringify(res))
    this.props.history.push('/list');
})

The response is recieved by call,

{"data":"","status":200,"statusText":"OK","headers":{"content-length":"0"},"config":{"url":"http://localhost:5000/User/login","method":"post","data":"{\"email\":\"a\",\"password\":\"a\"}","headers":{"Accept":"application/json, text/plain, /","Content-Type":"application/json;charset=utf-8"},"transformRequest":[null],"transformResponse":[null],"timeout":0,"xsrfCookieName":"XSRF-TOKEN","xsrfHeaderName":"X-XSRF-TOKEN","maxContentLength":-1},"request":{}}

But no cookie ends up being set, could somebody tell me what the issue here is? Thanks-

I also have

app.use(cookieParser());

as the first app use, as that was recommended, but this did not help

Upvotes: 2

Views: 662

Answers (2)

Sohail Ashraf
Sohail Ashraf

Reputation: 10604

The react app is not able to set cookie because the backend application is running on different port so it's cross domain cookie issue.

You have to set the below header in backend and in the Axios request set the withCredentials: true.

credentials: The request credentials you want to use for the request: omit, same-origin, or include. To automatically send cookies for the current domain, this option must be provided. Starting with Chrome 50.

In Axios

withCredentials indicates whether or not cross-site Access-Control requests should be made using credentials Default: withCredentials: false.

1. "Access-Control-Allow-Origin: http://localhost:3000";
2. "Access-Control-Allow-Credentials: true";
3. "Access-Control-Allow-Methods: GET, POST";
4. "Access-Control-Allow-Headers: Content-Type, *";

Example:

res
  .set("Access-Control-Allow-Origin", "http://localhost:3000")
  .set("Access-Control-Allow-Credentials", "true")
  .set("Access-Control-Allow-Methods", "GET, POST")
  .set("Access-Control-Allow-Headers", "Content-Type, *")
  .status(200).cookie('nameOfCookie', 'cookieValue', { maxAge: 1000 * 60 * 60 }).end();

Upvotes: 0

AleksW
AleksW

Reputation: 713

I have finally figured it out:

It turns out by default Axios has 'withCredentials' set to false, so I created a new instance with an override and used this instead

var myAxios = Axios.create ({
    withCredentials: true
})

This also required me to update cors to accept these credentials

app.use(cors({credentials: true, origin: 'http://localhost:3000'}));

Upvotes: 1

Related Questions