How to enable cors in Node js

devquora
devquora

Posted On: Dec 13, 2022

How to enable cors in Node js

 

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

    Please Login or Register to leave a response.

    Related Articles

    Node Js Tutorials

    Scheduling CRON Jobs on Node js using node schedule

    Cron Jobs are used for scheduling tasks to run on the server.CRON Jobs are the most commonly used method to automate tasks on Server. In this article, we will see how to schedule Jobs in Node.js. We a..

    Node Js Tutorials

    Uploading image from url using Node js

    In this tutorial, we are going to see how to Upload an image from URL using Node Js. We have written a simple function In Node.js to save an image from URL to local disk/ server. Whenever we use login..

    Node Js Tutorials

    Dropping an existing index from MongoDB or mongoose

    While working with MongoDB and Node js I face an issue. I have created mobile_no unique in starting and after some time I realized that I don't need my mobile_no to be unique. so I just go to my mode..