Skip to content

Instantly share code, notes, and snippets.

@lenivene
Created September 30, 2019 22:08
Show Gist options
  • Save lenivene/48741de16888ccb2a1853617a192b340 to your computer and use it in GitHub Desktop.
Save lenivene/48741de16888ccb2a1853617a192b340 to your computer and use it in GitHub Desktop.
Node JS: Adds CORS ( Cross-origin resource sharing ) headers to the response

EXAMPLE

CORS Express 4.x

const express = require('express');
const CORS = require( './modules/cross-origin.js' );

const app = express();
app.use( CORS );
/**
* Adds CORS ( Cross-origin resource sharing ) headers to the response
*
* @param {object} request the Request object
* @param {object} response the Response object
* @param {function} next function to continue execution
*
* @return {void}
*/
module.exports = ( request, response, next ) => {
response.set({
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'DELETE,HEAD,GET,PATCH,POST,PUT',
'Access-Control-Allow-Headers': 'Content-Type, Authorization'
});
if(request.method === 'OPTIONS') {
response.send(200);
} else {
next();
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment