Posted by Arjun Arjun on Thursday 22nd February 2018, 1 minute read

How to enable CORS in Express.js

How to CORS

In this post, you will learn about Cross-Origin Resource Sharing. Http requests are restricted by the same-origin policy, which means where scripts can be loaded from the same Origin. Specifically, the protocol, domain, and port must match. It means you can't send the request to other origins, this restriction is there for a security reason, it will prevent the attacks.

When you send a Cross-Origin request you will get errors similar to the below shown.
Chrome:

XMLHttpRequest cannot load http://localhost:3000. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.

Firefox:

Cross-Origin Request Blocked: The Same Origin Policy disallows How to enable CORS in Express.js s reading the remote resource at http://localhost:3000. (Reason: CORS header 'Access-Control-Allow-Origin' missing).

How to implement CORS

CORS is implemented through the Access-Control-Allow-Origin header. The easiest way to implement it in an Express application is to use the cors package (npm install --save cors).

To enable CORS for your application:

app.use(require('cors')());

That’s it. CORS is now enabled.

If you make a request to your app, you will notice a new header being returned:

Access-Control-Allow-Origin: *

The Access-Control-Allow-Origin header determines which origins are allowed to access server resources over CORS (the * wildcard allows access from any origin).

Limit CORS to specific routes

For example to restrict CORS to paths starting with /api

app.use('/api', require('cors')());

Restricting allowed hosts

If you want to restrict AJAX access to a single origin, you can use the origin option:

app.use(cors({
  origin: 'http://yourapp.com'
}));

If you would rather have a list of allowed origins, you can use a function instead of a string as the origin value:

var allowedOrigins = ['http://localhost:3000','http://yourapp.com'];

app.use(cors({

  origin: function(origin, callback){

    // allow requests with no origin

    // (like mobile apps or curl requests)

    if(!origin) return callback(null, true);

    if(allowedOrigins.indexOf(origin) === -1){

      var msg = 'The CORS policy for this site does not ' +

                'allow access from the specified Origin.';

      return callback(new Error(msg), false);

    }

    return callback(null, true);

  }
}));
...
Arjun

I am Arjun from Hyderabad (India). I have been working as a software engineer from the last 7+ years, and it is my passion to learn new things and implement them as a practice. Aside from work, I like gardening and spending time with pets.