Skip to content

Instantly share code, notes, and snippets.

@maztch
Created September 10, 2018 11:00
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 maztch/be48f737752129396e6917751797ae3a to your computer and use it in GitHub Desktop.
Save maztch/be48f737752129396e6917751797ae3a to your computer and use it in GitHub Desktop.
node CORS route sample
// all our previous code should be here
// this array is used for identification of allowed origins in CORS
const originWhitelist = ['http://localhost:3000', 'https://example.net'];
// middleware route that all requests pass through
router.use((request, response, next) => {
console.log('Server info: Request received');
let origin = request.headers.origin;
// only allow requests from origins that we trust
if (originWhitelist.indexOf(origin) > -1) {
response.setHeader('Access-Control-Allow-Origin', origin);
}
// only allow get requests, separate methods by comma e.g. 'GET, POST'
response.setHeader('Access-Control-Allow-Methods', 'GET');
response.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');
response.setHeader('Access-Control-Allow-Credentials', true);
// push through to the proper route
next();
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment