Skip to content

Instantly share code, notes, and snippets.

@therightstuff
Last active February 12, 2018 08:20
Show Gist options
  • Save therightstuff/4422ec81348722befc046fbafb3fbe01 to your computer and use it in GitHub Desktop.
Save therightstuff/4422ec81348722befc046fbafb3fbe01 to your computer and use it in GitHub Desktop.
CORS middleware for restify
// 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