Skip to content

Instantly share code, notes, and snippets.

@thomasyip
Created March 20, 2013 08:22
Show Gist options
  • Save thomasyip/5203134 to your computer and use it in GitHub Desktop.
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.
// 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