How can you allow CORS in Express.js?

Photo by Joan Gamell on Unsplash

How can you allow CORS in Express.js?

CORS is a node.js package for providing a Connect/Express middleware that can be used to enable CORS with various options.

$ npm install cors
var express = require('express')
var cors = require('cors')
var app = express()

app.use(cors())

app.get('/products/:id', function (req, res, next) {
  res.json({msg: 'This is CORS-enabled for all origins!'})
})

app.listen(80, function () {
  console.log('CORS-enabled web server listening on port 80')
})

Sources:

Express Cors Middleware. expressjs.com/en/resources/middleware/cors....