Created
April 9, 2012 16:02
-
-
Save cuppster/2344435 to your computer and use it in GitHub Desktop.
express.js middleware to support CORS pre-flight requests
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
app.use(express.methodOverride()); | |
// ## CORS middleware | |
// | |
// see: http://stackoverflow.com/questions/7067966/how-to-allow-cors-in-express-nodejs | |
var allowCrossDomain = function(req, res, next) { | |
res.header('Access-Control-Allow-Origin', '*'); | |
res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE'); | |
res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization'); | |
// intercept OPTIONS method | |
if ('OPTIONS' == req.method) { | |
res.send(200); | |
} | |
else { | |
next(); | |
} | |
}; | |
app.use(allowCrossDomain); |
Thanks again ))
WARNING: be aware that for authenticated cors requests, Access-Control-Allow-Origin can't be a wildcard '*'
https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS#Credentialed_requests_and_wildcards
Works!
@Lonniebiz please share a snippet of how you solved it.
Thank you so much!!!
Thank you!!
Great, it is helpful.
Very good!
This is Great stuff. it worked for me
Great, it works! Thank you.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
FYI for newer versions of Express, you will get a warning saying
res.send
is deprecated. Useres.sendStatus
instead