Enabling CORS in Node js
In this article, we are going to see how to enable CORS ( Cross-Origin Resource Sharing ) in Node JS. CORS essentially means cross-domain requests. Cross-Origin Resource Sharing (CORS) is a mechanism that uses additional HTTP headers to let a user agent gain permission to access selected resources from a server on a different origin (domain) then the site currently in use. A user agent makes a cross-origin HTTP request when it requests a resource from a different domain, protocol, or port than the one from which the current document originated. To enable CORS in Node Js simply add the below line of code. It will set a header on your response in the result CORS are enabled.
res.header("Access-Control-Allow-Origin", "*");
Use following code snippet to enable CORS for all resources on your Node server.
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(); });
Here is the complete code to enable CORS in Node Js:
var app = express(); 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(); }); app.get('/', function (req, res) { var data = { "results": [ "Anil", "Amit" ] }; res.json(data); }); app.get('/testCors', function(req, res){ var file = __dirname + '/ZipFile.zip'; res.download(file); // Set disposition and send it. });
That it, Thanks for Reading. Also, Read Node Js Interview Questions