Cross origin resource sharing (CORS)

When we are developing the web application, we come across situations where we need to host our frontend code and backend code on different domains. In this situation sometimes , we got an error (Access Control Allow Origin issue in Angular 2). We got this error when we try to access some resource that is on other domain. Here in this case the object from first domain cannot be able to communicate with the object in other domain.

To solve this type of problem in nodeJs and Angular2, we can use a node module named cors

npm install cors –save

var express = require('express');
var cors = require('cors');
var app = express();

var originsWhitelist = [
'http://localhost:4200', //this is front end url
'http://www.xyz.com' //production url
];
var corsOptions = {
origin: function(origin, callback){
var isWhitelisted = originsWhitelist.indexOf(origin) !== -1;
callback(null, isWhitelisted);
},
credentials:true
}
app.use(cors(corsOptions));

Above code will enable the cors on the server side.

By Pankaj Kumar Agarwal

Leave a reply:

Site Footer