6

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,
}))
Ahmed Hammad
  • 2,798
  • 4
  • 18
  • 35
  • 3
    `Access-Control-Allow-Origin` must be a hostname not `*` when you send cookies. – zerkms Sep 02 '18 at 23:14
  • please give more info about serverside code. ex.: `app.js` otherwise it seems like You're not using cookie parser – num8er Sep 02 '18 at 23:18
  • I added some info that may help. – Ahmed Hammad Sep 02 '18 at 23:24
  • 1
    What's the exact value of the `Access-Control-Allow-Origin` in the response? – zerkms Sep 02 '18 at 23:25
  • 1
    we need to see response headers from server. call: `curl -v -X OPTIONS http://localhost:8081` and put response to Your question – num8er Sep 02 '18 at 23:28
  • 3
    `Access-Control-Allow-Origin: *` so, as I mentioned 20 minutes ago you must pass a hostname not the `*` there. And that's what the error message exactly tells you as well. – zerkms Sep 02 '18 at 23:34
  • 1
    @zerkms YES, You are right, I had to change this to the hostname, as well as keeping the credentials options, and it works. Thank you so much guys. – Ahmed Hammad Sep 02 '18 at 23:40

2 Answers2

1

I know it's too late for OP, but for those who keep comming here - what helped me is:

app.use(cors({
  preflightContinue: true,
  credentials: true,
}));

source: https://expressjs.com/en/resources/middleware/cors.html

Ruslan
  • 21
  • 3
1

I got this problem and I fixed it by setting the header "Access-Control-Allow-Origin" to the URL of my frontend instead of "*"

More details: https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS/Errors/CORSNotSupportingCredentials

blocus
  • 41
  • 1
  • 6