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'标头。
我仅使用以下行:
res.header("Access-Control-Allow-Origin", "*");
而且有效。您有没有在发送标题之前打印任何其他内容的机会?标头必须先发送。中间件代码应优先于其他任何代码。
您确定代码正在执行吗?进行一些“ console.log”打印,以确保enableCORS
正在调用。
最后,使用chrome开发人员工具(或任何等效工具)查看从服务器返回的标头。对于chrome,请转到网络=>有问题的请求=>标头=>响应标头,并确保其中有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');
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句