请求的资源 node.js 上不存在 Access-Control-Allow-Origin 标头

use*_*221 8 jquery node.js cors

我在尝试通过 ajax 请求与我的 node.js 服务器通信时遇到问题。

我已经这样配置我的服务器:

var allowCrossDomain = function(req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type,      Accept");
  next();
};

app.use(allowCrossDomain);
Run Code Online (Sandbox Code Playgroud)

在执行我的请求时,我遇到此错误:

XMLHttpRequest cannot load http://10.192.122.180:8181/meters. No 'Access-Control-Allow-     Origin' header is present on the requested resource. Origin 'http://localhost:6161' is  therefore not allowed access.
Run Code Online (Sandbox Code Playgroud)

当我在浏览器中输入 URL 时,它就起作用了。我读过很多关于 CORS、同源政策的内容,但现在我很迷失。

有人可以帮我吗?

谢谢。

Zac*_*bit 0

allowCrossDomain我的猜测是,您在中间件 ( ) 有机会运行之前就正在提供页面服务。

如果您使用的是Express 3,请尝试以下操作:

app.use(allowCrossDomain);
app.use(app.router);
Run Code Online (Sandbox Code Playgroud)

如果您使用的是Express 4,请确保您的app.use(allowCrossDomain)呼叫位于其余路线(app.get等)之前。