繁体   English   中英

Node Express CORS请求

[英]Node Express CORS request

我有两个nodejs应用程序,服务器1运行UI代码,服务器2提供后端逻辑和api服务。 我正在尝试从服务器1中的UI应用程序调用$ .post jquery方法,该方法发布到服务器2中的api,我遇到了跨域限制错误,

我在app.js和UI Server(服务器1)的route / index.js中添加了以下代码,但没有成功。

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();
});

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();
});

我是nodejs / express的新手。

确保您的快速应用程序实际上在响应CORS OPTIONS请求。 浏览器首先在POST之前发送临时HTTP OPTIONS请求。 您的代码设置了标头,但实际上并未发送响应。 就像是:

router.options('/my/post/path', function (req, res) {
  console.log('Got CORS OPTIONS request for', req.originalUrl);
  res.send();
});

但是最终,正如mscdex所评论的那样,请使用npm中的cors中间件库而不是自己编写代码。 (尽管编写自己的代码作为学习练习是可以的)。

暂无
暂无

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

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