CORS 问题:请求的资源上不存在 'Access-Control-Allow-Origin' header
CORS issue: No 'Access-Control-Allow-Origin' header is present on the requested resource
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 时,我仍然收到错误消息 No 'Access-Control-Allow-Origin' header is present on the requested资源。
我只使用以下行:
res.header("Access-Control-Allow-Origin", "*");
并且有效。在发送 headers 之前,您是否有机会打印其他内容? headers 必须先发送。中间件代码应该优先于其他任何东西。
您确定代码正在执行吗?做一些 'console.log' 打印以确保 enableCORS
被调用。
最后,使用 chrome 开发人员工具(或任何等效工具)查看从服务器返回的 headers。对于 chrome,转到网络 => 有问题的请求 => headers => 响应 headers,并确保 CORS headers 在那里。
更新
尝试使用以下内容(摘自 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');
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 时,我仍然收到错误消息 No 'Access-Control-Allow-Origin' header is present on the requested资源。
我只使用以下行:
res.header("Access-Control-Allow-Origin", "*");
并且有效。在发送 headers 之前,您是否有机会打印其他内容? headers 必须先发送。中间件代码应该优先于其他任何东西。
您确定代码正在执行吗?做一些 'console.log' 打印以确保 enableCORS
被调用。
最后,使用 chrome 开发人员工具(或任何等效工具)查看从服务器返回的 headers。对于 chrome,转到网络 => 有问题的请求 => headers => 响应 headers,并确保 CORS headers 在那里。
更新 尝试使用以下内容(摘自 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');