0

Am trying to set Access-Control-Allow-Credentials header globally in Node Js using the CORS module configuration like this

`var cors = require('cors');
 var corsOptions = {
     origin: true,
     'Access-Control-Allow-Origin': 'localhost:1550'
     'Access-Control-Allow-Credentials': 'true'
 };

app.use(cors(corsOptions));`

This doesn't seem to work so I set it too for the route am trying to set a preflight response for. I set it like this

`router.options('/login', cors(corsOptions));`

I check on Chrome Developer Tools and I see Access-Control-Allow-Origin header is set but not Access-Control-Allow-Credentials. I need this header since I have set withCredentials = true in Angular.

Why is Node JS not setting Access-Control-Allow-Credentials header yet it sets the others?

I know this because am getting the following error in console

XMLHttpRequest cannot load http://www.localhost:1550/api/v1/auth/login. Response to preflight request doesn't pass access control check: Credentials flag is 'true', but the 'Access-Control-Allow-Credentials' header is ''. It must be 'true' to allow credentials. Origin 'http://127.0.0.1:1550' is therefore not allowed access.

2 Answers 2

4

I think you are not setting the configurations correctly. As in the documentation

https://www.npmjs.com/package/cors#configuration-options

 var corsOptions = {
 origin: 'localhost:1550',
 credentials : true
}

this will set the credentials header. As Origin sets Access-Control-Allow-Origin and credentials sets Access-Control-Allow-Credentials.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, I now realize that I had not gone throw the documentation thoroughly
1

You left out the details about what library if any you are using. Is it express? Post the full code.

Since you are just specifying the headers explicitly anyway you can drop the cors module. You can adapt this answer In Node.js/Express, how do I automatically add this header to every "render" response?

1 Comment

Am using Express, that code is pretty much it in terms of what I have written to handle the preflight request

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.