CORS setup

PHOTO EMBED

Tue Sep 21 2021 17:47:56 GMT+0000 (UTC)

Saved by @ExplodeMilk #typescript

npm install cors @types/cors

import cors from 'cors';
import express from 'express';

app = express();

// enable all routes
app.use(cors());

// enable single route
app.get('/route', cors(), function (req, res, next) {
  ...
})

// configure CORS
const corsOptions = {
  origin: 'http://example.com',
  optionsSuccessStatus: 200 // some legacy browsers (IE11, various SmartTVs) choke on 204
}

app.get('/route', cors(corsOptions), function (req, res, next) {
  ...
})

// enable pre-flight
app.options('/products/:id', cors()) // enable pre-flight request for DELETE request
app.del('/products/:id', cors(), function (req, res, next) {
  res.json({msg: 'This is CORS-enabled for all origins!'})
})
  
// enable pre-flight across-the-board
app.options('*', cors()) // include before other routes
content_copyCOPY

http://expressjs.com/en/resources/middleware/cors.html