Skip to content

How to enable CORS in Express.js

Last updated on November 21, 2022

In this post, you will learn about Cross-Origin Resource Sharing. HTTP requests are restricted by the same-origin policy, which means that 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 security reasons, and it will prevent 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);

  }
}));
0 0 votes
Article Rating
Subscribe
Notify of
guest

1 Comment
Most Voted
Newest Oldest
Inline Feedbacks
View all comments