Last active
February 12, 2018 08:20
-
-
Save therightstuff/4422ec81348722befc046fbafb3fbe01 to your computer and use it in GitHub Desktop.
CORS middleware for restify
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
// MIDDLEWARE | |
// must be defined before routing configured | |
server.use(restify.plugins.bodyParser()); | |
server.use(restify.plugins.queryParser()); | |
// CORS must be first | |
var allowedMethods = [ | |
"OPTIONS", | |
"GET", | |
"POST", | |
"PUT", | |
"DELETE" | |
]; | |
var allowedHeaders = [ | |
"X-Requested-With", | |
"Accept-Version", | |
"Content-Type" | |
]; | |
// add CORS access control headers to every request | |
server.use( | |
function crossOrigin(req, res, next) { | |
res.header("Access-Control-Allow-Origin", "*"); | |
res.header("Access-Control-Allow-Methods", allowedMethods.join()); | |
res.header("Access-Control-Allow-Headers", allowedHeaders.join()); | |
return next(); | |
} | |
); | |
// respond to pre-flight positively for CORS | |
// for regular node apps, use /.*/ or /\/api\/.*/ | |
// for node apps hosted on IISNODE, use /.*\/api\/.*/ | |
server.opts({ path: /.*/ }, function (req, res, next) { | |
res.send(200, 'PREFLIGHT SUCCESS'); | |
return next(); | |
}); | |
... |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment