How to add CORS functionality to your NodeJS web app
You can include a functionality to efficiently handle Cross domain requests. Known as CORS (Cross Origin Resource Sharing) it can be implemented on your NodeJS web application in the following two ways.
- Use
cors
npm module.
- This is easier and faster way to enable CORS in your application. First, installcors
module:
# npm install --save cors
- Now that cors
module is installed in your app, use it as middleware and you're done. All your requests are now CORS enabled:
## app.js
var express = require('express');
var cors = require('cors');
var app = express();
app.use(cors());
- You can also enable CORS on only a single request with the following code:
## app.js
var express = require('express');
var cors = require('cors');
var app = express();
app.get('/products/:id', cors(), function (req, res, next) {
res.json({msg: 'This is CORS-enabled for a Single Route'});
});
For more information you can refer to the documentation for cors
module here: https://www.npmjs.com/package/cors
- You can achieve the same, without requiring any external module if you are fine adding a few extra lines in your code. Add the following code to enable CORS functionality:
## app.js
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");
next();
});
nodejsagenecy.com doesnt work
Doen’t work for me =(