Skip to content

Instantly share code, notes, and snippets.

@jalalhejazi
Created April 22, 2013 12:53
Show Gist options
  • Save jalalhejazi/5434681 to your computer and use it in GitHub Desktop.
Save jalalhejazi/5434681 to your computer and use it in GitHub Desktop.
Nodejs: CORS support in Node server.js
// please read before code any CORS:
// http://john.sh/blog/2011/6/30/cross-domain-ajax-expressjs-and-access-control-allow-origin.html
// http://stackoverflow.com/questions/7067966/how-to-allow-cors-in-express-nodejs
//
setHeaders = function (req,res,next) {
res.header("X-Powered-By","nodejs");
// if ajax set access control
if (req.xhr)
{
res.header("Access-Control-Allow-Origin", req.header('origin'));
res.header("Access-Control-Allow-Headers", "X-Requested-With");
}
next();
};
// then apply that function to all routes via
app.use(setHeaders);
// (usually within app.configure())
//*******************************************************************************//
app.all('/posts', function(req, res){
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "X-Requested-With");
res.send(
{ posts : '...' }
);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment