Clue Mediator

How to enable CORS in Node.js

πŸ“…March 24, 2020
πŸ—Node.js

Today we'll show you how to enable CORS in Node.js. Most of the beginners are facing the CORS issue while they are working with API creation and access it through some other application.

Enabling CORS in Node.js, Express cors middleware - Express.js, ExpressJS - enable cross-origin resource sharing, Handling CORS in Express, node js cors allow all, express allow cors localhost, express cors access-control-allow-origin, enable cors node http server, express cors not working, express.static cors, node js fetch cors, node js bypass cors.

Checkout more articles on Node.js

CORS 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. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

When does the error occur?

CORS error will occur while you are sharing the resources between cross-origin. In other words, when you are working with API and sharing the data with different origins then Cross-origin resource sharing (CORS) error will occur.

Replicate CORS error

I would recommend you to check the article: Create REST API in Node.js. Here we are slightly updating the code to handle the JSON response. For that we will use body-parser npm package.

After implementing the package, your code should look like below.

server.js

var express = require('express'),
  bodyParser = require('body-parser'),
  app = express(),
  port = process.env.PORT || 4000;

// parse application/json
app.use(bodyParser.json());
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: true }));

// request handlers
app.get('/', (req, res) => {
  res.status(200).json({ message: 'Enable CORS in Node.js - Clue Mediator' });
});

app.listen(port, () => {
  console.log('Server started on: ' + port);
});

Now try to access this get API through other application like React, Angular, etc and check the console where you will see the CORS error.

Note: Above API code will work with Postman but it will not work with other front end applications.

So let's see how to fix it.

Different ways to enable CORS

  1. Enable CORS without external module
  2. Enable CORS using npm package

1. Enable CORS without external module

To enable CORS without an external module or npm package, we have to simply write a few lines of the code in a server file.

// enable CORS without external module
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 we allowed all the origin to access this app by passing `*` in `Access-Control-Allow-Origin`. You can pass a single domain to share resources with a given domain only.

res.header("Access-Control-Allow-Origin", "http://yourdomain.com");

Note: Do not set `/` at the end of the URL. like `http://yourdomain.com/`. This will not work.

Let's combine all code together and see how it looks.

server.js

var express = require('express'),
  bodyParser = require('body-parser'),
  app = express(),
  port = process.env.PORT || 4000;

// enable CORS without external module
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();
});

// parse application/json
app.use(bodyParser.json());
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: true }));

// request handlers
app.get('/', (req, res) => {
  res.status(200).json({ message: 'Enable CORS in Node.js - Clue Mediator' });
});

app.listen(port, () => {
  console.log('Server started on: ' + port);
});

2. Enable CORS using npm package

This is another way to enable CORS using the npm package. We'll use cors npm package to do it. Run the following command to install the package.

npm i cors

After successful installation, we have to add it in `server.js` file and enable the CORS.

// enable CORS using npm package
var cors = require('cors');
app.use(cors());

So at last your `server.js` file should look like below.

server.js

var express = require('express'),
  bodyParser = require('body-parser'),
  app = express(),
  port = process.env.PORT || 4000;

// enable CORS using npm package
var cors = require(β€˜cors’);
app.use(cors());

// parse application/json
app.use(bodyParser.json());
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: true }));

// request handlers
app.get('/', (req, res) => {
  res.status(200).json({ message: 'Enable CORS in Node.js - Clue Mediator' });
});

app.listen(port, () => {
  console.log('Server started on: ' + port);
});

You can also enable CORS on an individual request. Check the following code.

// request handlers
app.get('/', cors(), (req, res) => {
  res.status(200).json({ message: 'Enable CORS in Node.js - Clue Mediator' });
});

Note: To allow cors on an individual request, no need to set `app.use(cors())` in the `server.js` file.

That’s it. CORS is now enabled.

Thank you for reading. Happy Coding!

Demo & Source Code

Github Repository