Skip to content

Instantly share code, notes, and snippets.

@ritwickdey
Last active November 21, 2018 06:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ritwickdey/36682dabe4a992c57e4562c935bfbbdd to your computer and use it in GitHub Desktop.
Save ritwickdey/36682dabe4a992c57e4562c935bfbbdd to your computer and use it in GitHub Desktop.
CORS Setup for Node.js
const express = require('express');
const app = express();
//CORS Setup
app.use((req, res, next) => {
res.header('Access-Control-Allow-Origin', '*'); // Allowed Origins.
res.header('Access-Control-Allow-Headers', '*'); // Allowed Headers.
res.header('Access-Control-Expose-Headers', 'token'); // Exposed Headers - means client only can access those headers.
if (req.method === 'OPTIONS') {
res.header('Access-Control-Allow-Methods', 'PUT, POST, PATCH, DELETE'); // Allowed Methods.
res.header('Access-Control-Max-Age', 5 * 24 * 60 * 60); //5 days... But Chrome will take its MAX value. :D
return res.status(200).json({});
}
next();
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment