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” header 。
最佳答案
我只使用以下行:
res.header("Access-Control-Allow-Origin", "*");
而且它有效。在发送标题之前您是否有可能打印其他内容? header 必须先于其他内容发送。中间件代码应该优先于其他任何代码。
您确定代码正在执行吗?执行一些“console.log”打印以确保正在调用enableCORS
。
最后,使用 chrome 开发者工具(或任何等效工具)查看从服务器返回的 header 。对于 Chrome,请转到网络 => 有问题的请求 => header => 响应 header ,并确保 CORS header 存在。
更新 尝试使用以下内容(取自 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');
关于node.js - CORS问题: No 'Access-Control-Allow-Origin' header is present on the requested resource,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35316443/