How to pass cookies through CORS?

Viewed 8626

I have a project that sends HTTP requests from the client using Axios

axios.create({
    baseURL: `http://localhost:8081/`,
    withCredentials: true
  })

And I suppose this allows cookies -Which I am sure it shows in the browser before you ask- to be sent with the requests.

The problem occurs in the back-end, when this error shows in the log:

Response to preflight request doesn't pass access control check: The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'. Origin 'http://localhost:8080' is therefore not allowed access. The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute.

I tried this:

app.use(cors({
  //origin : to be set later
  credentials: true,
}))

and this instead:

app.use(function(req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Authorization");
  res.header("Access-Control-Allow-Credentials", true);
  next();
});

but neither seems to work.

EDIT - Here is the answer for future visitors

With the help of the participants in comments, I found out I had to set the origin value:

app.use(cors({
  origin : "http://localhost:8080",
  credentials: true,
}))
2 Answers
Related