CORS with Express

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' )(); app.use( require ( 'cors' )()); app.get( '/' , (req, res) => res.send( 'Hello, World!' )); const server = await app.listen( 3000 ); 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' )(); 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 ); const axios = require ( 'axios' ); let res = await axios.get( 'http://localhost:3000' ); res.headers[ 'access-control-allow-origin' ]; res = await axios.get( 'http://localhost:3000/api/test' ); res.headers[ 'access-control-allow-origin' ];

Want to become your team's Express expert? There's no better way to really grok a framework than to write your own clone from scratch. In 15 concise pages, this tutorial walks you through how to write a simplified clone of Express called Espresso. Get your copy!



Espresso supports: Route handlers, like `app.get()` and `app.post()`

Express-compatible middleware, like `app.use(require('cors')())`

Express 4.0 style subrouters As a bonus, Espresso also supports async functions, unlike Express.



Get the tutorial and master Express today!

More Express Tutorials