/

Handling CORS in Express: Enabling Cross-Origin Requests

Handling CORS in Express: Enabling Cross-Origin Requests

Cross-Origin Resource Sharing (CORS) is a mechanism that allows JavaScript applications running in a browser to make HTTP requests to servers on different domains, subdomains, ports, or protocols. By default, browsers enforce the same-origin policy, which means that cross-origin requests are not allowed.

To enable cross-origin requests in your Express application, you need to set up a CORS policy on the server. This is particularly important when working with modern browser features such as ES Modules.

Here’s an example of how to handle CORS in Express:

Browser Support

CORS is supported by all modern browsers except for IE<10.

Example with Express

If you are using Node.js and Express, you can use the cors middleware package to handle CORS.

First, install the cors package by running the following command:

1
npm install cors

Then, require and use the cors package in your Express server:

1
2
3
4
5
6
7
8
9
10
11
12
13
const express = require('express');
const cors = require('cors');
const app = express();

app.get('/with-cors', cors(), (req, res, next) => {
res.json({ msg: 'CORS enabled: cross-origin request successful!' });
});

// Rest of the app

app.listen(3000, () => {
console.log('Listening on port %s', server.address().port);
});

In the above example, the /with-cors endpoint is configured to allow cross-origin requests by using the cors() middleware function.

You can also configure the server to allow specific origins to serve, and block others. This can be done by passing an object with the origin key to the cors() function:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
const whitelist = ['http://example1.com', 'http://example2.com'];
const corsOptions = {
origin: function (origin, callback) {
if (whitelist.indexOf(origin) !== -1) {
callback(null, true);
} else {
callback(new Error('Not allowed by CORS'));
}
},
};

app.get('/products/:id', cors(corsOptions), (req, res, next) => {
//...
});

In the above example, only requests from http://example1.com and http://example2.com will be allowed. All other origin requests will be blocked.

Preflight Requests

Certain requests, such as GET, POST, and HEAD, are considered simple requests and are handled without an additional preflight phase. Other requests must go through a pre-approval phase called a preflight request. The browser sends an OPTIONS request to the server to check permissions before making the actual request.

To handle preflight requests in Express, you can use the options() method:

1
app.options('/the/resource/you/request', cors());

In the above example, the options() method is used to allow preflight requests on a specific resource.

It is also possible to allow preflight requests for all resources by using a wildcard:

1
app.options('*', cors());

Tags: CORS, Express, Node.js, Cross-Origin Resource Sharing, JavaScript