简体   繁体   中英

Node Express CORS request

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.

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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM