node js cors
When we are trying to access the resource from other domain or server we will getting cors errors or according to google search:
What is CORS? ... CORS errors are common in web apps when a cross-origin request is made but the server doesn't return the required headers in the response (is not CORS-enabled): XMLHttpRequest cannot load api.example.com. No 'Access-Control-Allow-Origin' header is present on the requested resource
How we handle cors errors in our node/express applications:
First step is to install node.js cors package using below command
npm i --save cors
In case we want to setup cors for all the routes in the application. We need to add cors middleware in app.js file like this:
var cors = require('cors');
var app = express();
app.use(cors());
By default above statement will enable cors for all the requests, in case we want to restrict the request for single domain, we need to add some options and pass into the cors middleware like this:
var cors = require('cors');
var app = express();
var corsOpt = {
origin: 'your domain url for we want to enable cors',
}
app.use(cors(corsOpt));
How to setup cors for single route in our node/express application. Open your route file and add cors as middleware in that particular route
var cors = require('cors')
var app = express();
var corsOpt = {
origin: 'your domain url for we want to enable cors',
}
router.get('/users', cors(corsOpt), function(req, res, next) {
res.json([{
"id": 1,
"firstname": "first name",
"lastname": "last name"
},{
"id": 2,
"firstname": "first name 2",
"lastname": "last name 2"
}]);
});