问题描述
var enableCORS = function(req, res, next) {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');
res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization, Content-Length, X-Requested-With');
// intercept OPTIONS method
if ('OPTIONS' == req.method) {
res.send(200);
}
else {
next();
}
};
app.use(enableCORS);
我发现要在服务器端使用以下代码段,但是当我尝试进行POST时,仍然收到错误消息:所请求的资源上没有'Access-Control-Allow-Origin'标头.
I found out to use the following snippet in the server side, but still when i try to POST I am getting the error No 'Access-Control-Allow-Origin' header is present on the requested resource.
推荐答案
我仅使用以下行:
res.header("Access-Control-Allow-Origin", "*");
它有效.您有没有在发送标题之前打印任何其他内容的机会?标头必须先发送.中间件代码应优先于其他任何东西.
And it works. Any chance you print anything else before sending the headers? headers must be sent before anything else. The middleware code should be prior to anything else.
您确定代码正在执行吗?执行一些"console.log"打印以确保正在调用enableCORS
.
Are you sure the code is getting executed? do some 'console.log' prints to make sure the enableCORS
is being called.
最后,使用chrome开发人员工具(或任何等效工具)查看从服务器返回的标头.对于chrome,请转到网络=>有问题的请求=>标头=>响应标头,并确保CORS标头在其中.
Lastly, use chrome developer tools (or any equivalent tool) to view the headers returned from the server. For chrome, go to network => the problematic request => headers => Response headers, and make sure the CORS headers are there.
更新尝试使用以下内容(摘自此处):
UpdateTry using the following (taken from here):
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE'); # OPTIONS removed
res.header('Access-Control-Allow-Headers', 'Content-Type');
这篇关于CORS问题:所请求的资源上不存在"Access-Control-Allow-Origin"标头的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!