我在不同的端口 (8000,8001) 上运行后端和前端,我无法从快速服务器创建 res.redirect(...) 并且浏览器显示 CORS 错误(访问 XMLHttpRequest at...) .
这是 MEVN(Mongo、Express、Vue、Nodejs)应用程序,Vue 前端和 express(nodejs) 后端在不同的端口上运行。我在后端实现了 cors() ,它使我的前端可以发出请求(获取、发布)但后端仍然无法使用 res.redirect("...") 重定向前端页面,因为它显示 CORS错误。
// Backend
var cors = require('cors');
app.use(cors())
...
function (req, res, next){ // some middleware on backend
...
res.redirect('http://urltofrontend'); // cause error
// Error msg on Chrome
Access to XMLHttpRequest at 'http://localhost:8001/' (redirected from
'http://localhost:8000/api/login') from origin 'null' has been blocked
by CORS policy: Request header field content-type is not allowed by
Access-Control-Allow-Headers in preflight response.
我已经完成了 cors() 的实现,它允许我的前端向我的后端发出 http 请求,并且运行良好。但是,来自后端的 res.redirect( ...) 被 CORS 错误阻止。
最佳答案
要解决浏览器中的 CORS 错误,您应该将以下 HTTP header 添加到响应中:
Access-Control-Allow-Headers: Content-Type
您可以通过添加以下代码来实现:
app.use(cors({
'allowedHeaders': ['Content-Type'],
'origin': '*',
'preflightContinue': true
}));
关于node.js - 后端和前端在不同端口上运行,CORS 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54531235/