【发布时间】:2014-04-09 10:41:00
【问题描述】:
我在尝试通过 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);
执行我的请求时出现此错误:
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.
当我在浏览器中输入 URL 时,它可以工作。我已经阅读了很多关于 CORS、同源政策的内容,但现在我很迷茫。
有人可以帮帮我吗?
谢谢。
【问题讨论】:
-
添加
Access-Control-Allow-Origin是正确的,但您的代码似乎没有添加它。使用网络选项卡上的 Firebug 或 Chrome 开发工具检查标头。 -
很高兴看到也发出请求的前端代码。在过去的几个小时里,我一直在与类似的问题作斗争。我在发送格式错误的 POST 数据时遇到了问题(使用 jquery)。我有两个标题,还有
res.header('Access-Control-Allow-Methods', 'POST');,你可以用逗号分隔'POST, GET'等指定多个休息方法。这可能会有所帮助