Created
April 22, 2013 12:53
-
-
Save jalalhejazi/5434681 to your computer and use it in GitHub Desktop.
Nodejs: CORS support in Node server.js
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
// 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