Created
March 20, 2013 08:22
-
-
Save thomasyip/5203134 to your computer and use it in GitHub Desktop.
Cheatsheet for adding CORS supports to an ExpressJS app. I found that the most reliable way of sending CORS headers is to echo back what the browser sent to the server. Reminder to test it with browser cache disable and cleared at least one.
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
// CORS | |
app.use(function(req, res, next) { | |
if ('OPTIONS' !== req.method) { | |
if ('origin' in req.headers) { | |
res.setHeader('Access-Control-Allow-Origin', req.headers.origin); | |
} | |
next(); | |
} else { | |
var body = '{}\n'; | |
if ('origin' in req.headers) { | |
if (ALLOWED_ORIGINS.indexOf(req.headers.origin) >= 0) { | |
res.setHeader('Content-Type', 'application/json'); | |
res.setHeader('Content-Length', body.length); | |
res.setHeader('Access-Control-Allow-Origin', req.headers.origin); | |
res.setHeader('Access-Control-Allow-Headers', req.headers['access-control-request-headers']); | |
if (req.headers['access-control-request-method']) { | |
res.setHeader('Access-Control-Allow-Method', req.headers['access-control-request-method']); | |
} | |
if (req.headers['access-control-request-methods']) { | |
res.setHeader('Access-Control-Allow-Methods', req.headers['access-control-request-methods']); | |
} | |
res.setHeader('Access-Control-Max-Age', (60)); | |
res.setHeader('Access-Control-Allow-Credentials', 'true'); | |
res.end(body); | |
} else { | |
res.setHeader('Content-Type', 'application/json'); | |
res.setHeader('Content-Length', body.length); | |
res.send(403, body); | |
res.end(); | |
} | |
} | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment