Node.js 我的节点应用程序中的CORS不工作
某网站正在对我的节点应用程序执行XMLHttpRequest,但他们收到以下错误:Node.js 我的节点应用程序中的CORS不工作,node.js,express,http-status-code-504,Node.js,Express,Http Status Code 504,某网站正在对我的节点应用程序执行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 resp
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));
这是节点应用程序中的代码(表示不相关的代码):
你知道为什么这样不行吗
谢谢您的建议。尝试添加
选项作为允许的方法之一
基本上替换res.header('Access-Control-Allow-Methods','GET,POST')代码>带有res.header('Access-Control-Allow-Methods','OPTIONS,GET,POST')代码>我是提出这个问题的人
我找到了答案
如果XMLHttpRequest打开请求设置为asynchronous(第三个参数设置为'true'),则节点应用程序必须发送响应。状态代码是不够的。你必须做出某种回应。否则会出现504超时错误
编辑:您可以使用res.sendStatus(200)。我的错误是我只是在做res.status(200)。谢谢你的回复。我试过了,但还是有同样的问题。我的应用程序在nginx反向代理后面。这会影响到事情吗?可能吧。您可以发布应用程序从服务器返回的标题吗?响应为空。我收到一个504(超时)错误。然而,如果我尝试使用一个简单的GET请求访问我的节点应用程序,它就可以正常工作。奇怪…我知道了。请看下面!你为什么不利用cors图书馆?我是?var cors=require('cors')
...
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);
});