Created
September 10, 2018 11:00
-
-
Save maztch/be48f737752129396e6917751797ae3a to your computer and use it in GitHub Desktop.
node CORS route sample
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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