2

一个网站正在对我的节点应用程序执行 XMLHttpRequest,但他们收到以下错误:

XMLHttpRequest cannot load http://[MY IP]/start. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://www.[THEIR WEBSITE].com' is therefore not allowed access. The response had HTTP status code 504.

这是他们的 XMLHttpRequest 请求:

var xhr = typeof XMLHttpRequest === "undefined" ? new ActiveXObject("Microsoft.XMLHTTP") : new XMLHttpRequest; 
xhr.open("POST", 'http://[MY IP]/myapp', true);
xhr.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
xhr.send(JSON.stringify(data));

这是节点应用程序中的代码(... 代表不相关的代码):

...
var cors = require('cors')
...
app.use(function(req, res, next) {
  res.header('Access-Control-Allow-Origin', '*');
  res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept');
  res.header('Access-Control-Allow-Methods', 'GET,POST');
  next();
});

app.post('/myapp', function (req, res) {
  var data = req.body;
  console.log(data);
  res.status(200);
});

你知道为什么这不起作用吗?

谢谢你的建议。

4

2 回答 2

1

我是提出这个问题的人。

我想出了答案。

如果 XMLHttpRequest 打开请求设置为异步(第三个参数设置为“true”),则节点应用程序必须发送响应。状态码是不够的。你必须提供某种回应。否则会出现 504 超时错误。

编辑:您可以使用res.sendStatus(200)。我的错误是我只是在做 res.status(200)。

于 2016-03-15T09:44:35.830 回答
0

尝试添加OPTIONS为允许的方法之一。

基本上替换res.header('Access-Control-Allow-Methods', 'GET,POST');res.header('Access-Control-Allow-Methods', 'OPTIONS,GET,POST');

于 2016-03-15T06:38:02.130 回答