-
-
Save ThomasBurleson/b4495d1e89d1a1e1bbd3 to your computer and use it in GitHub Desktop.
CORS checking with NodeJS
This file contains hidden or 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
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()); | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Forked based on (Jose Luis Rivas [email protected]):
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: