一个网站正在对我的节点应用程序执行 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);
});
你知道为什么这不起作用吗?
谢谢你的建议。