Reputation: 2264
I have two nodejs apps, server 1 running UI code, Server 2 provides back end logic and api services. I'm trying to call $.post jquery method from UI app in server 1 which posts to api in server 2, I'm getting cross domain restriction error,
I added the following code in app.js and routes/index.js in UI Server (server 1), but no vain.
app.js file
enter code here
app.use( function(req, res, next) {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');
res.header('Access-Control-Allow-Headers', 'X-Requested-With, X-HTTP-Method-Override, Content-Type, Accept');
next();
});
routes/index.js file
router.use( function(req, res, next) {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');
res.header('Access-Control-Allow-Headers', 'X-Requested-With, X-HTTP-Method-Override, Content-Type, Accept');
next();
});
I'm new to nodejs/express.
Upvotes: 2
Views: 847
Reputation: 145994
Make sure your express app is actually responding to the CORS OPTIONS request. The browser with first send a provisional HTTP OPTIONS request before the POST. Your code sets headers but doesn't actually send responses. Something like:
router.options('/my/post/path', function (req, res) {
console.log('Got CORS OPTIONS request for', req.originalUrl);
res.send();
});
But ultimately as mscdex commented, use a cors middleware library from npm instead of coding your own. (Although coding your own is fine as a learning exercise).
Upvotes: 3