Skip to content

Instantly share code, notes, and snippets.

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 ThomasBurleson/b4495d1e89d1a1e1bbd3 to your computer and use it in GitHub Desktop.
Save ThomasBurleson/b4495d1e89d1a1e1bbd3 to your computer and use it in GitHub Desktop.
CORS checking with NodeJS
function unkMH(req, res) {
var allowHeaders;
if (req.method.toLowerCase() === 'options') {
allowHeaders = ['Accept', 'Accept-Version', 'Content-Type', 'Api-Version', 'Authorization'];
if (res.methods.indexOf('OPTIONS') === -1) {
res.methods.push('OPTIONS');
}
res.header('Access-Control-Allow-Credentials', true);
res.header('Access-Control-Allow-Headers', allowHeaders.join(', '));
res.header('Access-Control-Allow-Methods', res.methods.join(', '));
res.header('Access-Control-Allow-Origin', req.headers.origin);
return res.send(204);
} else {
return res.send(new restify.MethodNotAllowedError());
}
};
@ThomasBurleson
Copy link
Author

Forked based on (Jose Luis Rivas ghostbar38@gmail.com):

I got stuck at one point while calling REST service from my Angular JS code

Capture the OPTIONS requests and send that in the data, don't send it on
all of them.

CORS have something called "preflight" and it's a request sent before
the request you want to do, it's called OPTIONS and looks for that.

On my backends with Express.js and Restify, I just wait at the end of the routes if
something was not called then I put a middleware to check if it's an
OPTIONS method request and if so push back the headers, this was the
prototype I built for someone else that made the same question here last
year:

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment