我的节点应用程序中的CORS不起作用

一个网站正在做一个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); }); 

你有什么想法,为什么这不工作?

谢谢你的build议。

我是造成这个问题的人。

我想出了答案。

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

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

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

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