Home ยป How to enable CORS in Node.js

How to enable CORS in Node.js

Enabling CORS in Node.js Made Easy
Today, we’ll demystify CORS (Cross-Origin Resource Sharing) in Node.js. Many beginners encounter CORS issues when working on API creation and accessing it from different applications.

Understanding the CORS Error

Ever seen this error? “Access to fetch at ‘<BACK_END_URL>’ from origin ‘<FRONT_END_URL>’ has been blocked by CORS policy: No ‘Access-Control-Allow-Origin’ header is present on the requested resource.” This happens when sharing resources across origins, such as working with APIs and sharing data with different sources.

Replicating the CORS Error

We recommend checking our article on “Creating a REST API in Node.js” where we update the code to handle JSON responses using the “body-parser” npm package. After implementing it, you’ll encounter the CORS error when accessing the API from front-end applications like React or Angular.

Different Approaches to Enable CORS

1. Enable CORS Without External Modules:
To enable CORS without external modules or npm packages, add these lines of code to your server file:

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");

Here, we allow all origins to access the app by using “*” in “Access-Control-Allow-Origin.” You can specify a single domain to share resources with a particular source.

2. Enable CORS Using npm Package:
Another way is to use the “cors” npm package. Install it with the following command:

npm i cors

After installation, add it to your server.js file and enable CORS like this:

var cors = require('cors');

Your server.js file should then look like this.

These methods empower you to tackle CORS effectively, ensuring smooth interactions between your Node.js server and various front-end applications.

Thank you for reading. Happy coding!


1 Comment

Click here to post a comment

21 − = 19