简体   繁体   English

Node Express CORS请求

[英]Node Express CORS request

I have two nodejs apps, server 1 running UI code, Server 2 provides back end logic and api services. 我有两个nodejs应用程序,服务器1运行UI代码,服务器2提供后端逻辑和api服务。 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, 我正在尝试从服务器1中的UI应用程序调用$ .post jquery方法,该方法发布到服务器2中的api,我遇到了跨域限制错误,

I added the following code in app.js and routes/index.js in UI Server (server 1), but no vain. 我在app.js和UI Server(服务器1)的route / index.js中添加了以下代码,但没有成功。

app.js file app.js文件

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 route / index.js文件

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. 我是nodejs / express的新手。

Make sure your express app is actually responding to the CORS OPTIONS request. 确保您的快速应用程序实际上在响应CORS OPTIONS请求。 The browser with first send a provisional HTTP OPTIONS request before the POST. 浏览器首先在POST之前发送临时HTTP OPTIONS请求。 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. 但是最终,正如mscdex所评论的那样,请使用npm中的cors中间件库而不是自己编写代码。 (Although coding your own is fine as a learning exercise). (尽管编写自己的代码作为学习练习是可以的)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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