2
votes

When trying to redirect the user to the login page, I always get this error:

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 'null' is therefore not allowed access. The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute.

On my express application, I already implemented CORS:

var corsOptions = {
  origin:  'http://localhost:4200',
  credentials: true
}

app.use(cors(corsOptions));

Then I try to redirect the user:

router.use(function(req,res,next){
    if((req.session.user == null){
        res.redirect('http://localhost:4200' + '/login')
    }
    else
        next();
});

On Angular 4 I'm sending all requests with {withCredentials : true}, because I'm using cookies;

These are the request/response headers:

Response:

Access-Control-Allow-Credentials:true Access-Control-Allow-Origin:http://localhost:4200 Connection:keep-alive Date:Thu, 10 Aug 2017 12:09:55 GMT Location:http://localhost:4200/login set-cookie:semanaintegrada.session=s%3A6nieAv1pfn2V-2x7H4HbnqJFbYsgJmwy.hO1QKm%2Fgm6Kmso8pLCQ5zrZAVNhIYgfr%2BgzOB0oI9UA; Path=/; Expires=Thu, 10 Aug 2017 13:09:55 GMT Transfer-Encoding:chunked Vary:Origin X-Powered-By:Express

Request:

Accept:application/json, text/plain, / Accept-Encoding:gzip, deflate, br Accept-Language:pt-BR,pt;q=0.8,en-US;q=0.6,en;q=0.4 Cache-Control:no-cache Connection:keep-alive Content-Length:39 content-type:application/json Cookie:semanaintegrada.session=s%3AwuiVwYs3Ahs4dfLULfpqMBcrnbthY7sZ.OYZk%2FCnZGHAe8v1T8nWpbAdFQVsXjUFAQxnYI27%2FZlE Host:localhost:3000 Origin:http://localhost:4200 Pragma:no-cache Referer:http://localhost:4200/ User-Agent:Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.90 Safari/537.36

Also, in Chrome there are 4 requests that are created ( I dont know why ). 3 to my express app and 1 to localhost:4200 The last one have Access-Control-Allow-Origin:* and Origin null Could this be related?

1

1 Answers

1
votes

"credentials flag" refers to XMLHttpRequest.withCredentials of the request being made, not to an Access-Control-Allow-Credentials header.

If the request's withCredentials is true, Access-Control-Allow-Origin: * can't be used, even if there is no Access-Control-Allow-Credentials header.