Created
July 4, 2014 01:17
-
-
Save awsp/dfa6da5d6fb061310d07 to your computer and use it in GitHub Desktop.
Add header to allow CORS in Node JS
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Add header to allow CORS in node | |
* Require express | |
* | |
* Quoting from http://stackoverflow.com/questions/18310394/no-access-control-allow-origin-node-apache-port-issue | |
*/ | |
app.use(function (req, res, next) { | |
// Website you wish to allow to connect | |
res.setHeader('Access-Control-Allow-Origin', 'http://localhost:8888'); | |
// Request methods you wish to allow | |
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE'); | |
// Request headers you wish to allow | |
res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type'); | |
// Set to true if you need the website to include cookies in the requests sent | |
// to the API (e.g. in case you use sessions) | |
res.setHeader('Access-Control-Allow-Credentials', true); | |
// Pass to next layer of middleware | |
next(); | |
}); | |
app.listen(3000); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
its not working though I have included above code in my NODE App and making POST request in Angular. I am using Chrome
Access to XMLHttpRequest at 'http://localhost:8080/employees/create' from origin 'http://localhost:4200' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
employee.service.ts:53 Error HttpErrorResponse {headers: HttpHeaders, status: 0, statusText: "Unknown Error", url: "http://localhost:8080/employees/create ", ok: false, …}