CORS问题:请求的资源上没有“Access-Control-Allow-Origin”标题

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); 

我发现在服务器端使用下面的代码片段,但仍然当我尝试发布我得到的错误没有“访问控制允许来源”标题出现在请求的资源。

我只使用以下行:

 res.header("Access-Control-Allow-Origin", "*"); 

它工作。 在发送标题之前,你有没有打印其他的东西? 标题必须在其他之前发送。 中间件代码应该在别的之前。

你确定代码正在执行吗? 做一些“console.log”打印,以确保调用enableCORS

最后,使用chrome开发者工具(或任何等效的工具)查看从服务器返回的头文件。 对于chrome,请转到networking=>有问题的请求=>标题=>响应标题,并确保CORS标题在那里。

更新尝试使用以下(从这里取得 ):

 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');