CORS with Express

Sep 12, 2019

CORS headers allow apps running in the browser to make requests to servers on different domains (also known as origins). CORS headers are set on the server side - the HTTP server is responsible for indicating that a given HTTP request can be cross-origin.

The cors npm module is an Express middleware that sets CORS headers on the Express response object.

const app = require('express')();
// Set CORS headers on all responses
app.use(require('cors')());

app.get('/', (req, res) => res.send('Hello, World!'));
const server = await app.listen(3000);

// Make an example request to see that, yep, the CORS headers are set
const axios = require('axios');
const res = await axios.get('http://localhost:3000');
res.headers['access-control-allow-origin']; // '*'

You can also declare CORS middleware on a certain subset of your routes by passing a string parameter to use().

const app = require('express')();
// Set CORS headers on responses to any requests whose URL starts with
// '/api'
app.use('/api', require('cors')());

app.get('/api/test', (req, res) => res.json({ ok: 1 }));
app.get('/', (req, res) => res.send('Hello, World!'));
const server = await app.listen(3000);

// Make an example request to see that CORS headers are set on
// `/api/test`, but not `/`
const axios = require('axios');
let res = await axios.get('http://localhost:3000');
res.headers['access-control-allow-origin']; // undefined

res = await axios.get('http://localhost:3000/api/test');
res.headers['access-control-allow-origin']; // '*'

More Express Tutorials