后端和前端在不同端口上运行,后端重定向时出现 CORS 错误

2024-04-11

我在不同的端口(8000,8001)上运行后端和前端,我无法从 Express 服务器进行 res.redirect(...) 并且浏览器显示 CORS 错误(访问 XMLHttpRequest at...)。

这是MEVN(Mongo,Express,Vue,Nodejs)应用程序,Vue前端和express(nodejs)后端运行在不同的端口上。我在后端实现了 cors() ,它使我的前端可以发出请求(get、post),但后端仍然无法使用 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 标头添加到响应中:

Access-Control-Allow-Headers: Content-Type

您可以通过添加以下代码来做到这一点:

app.use(cors({
  'allowedHeaders': ['Content-Type'],
  'origin': '*',
  'preflightContinue': true
}));
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

后端和前端在不同端口上运行,后端重定向时出现 CORS 错误 的相关文章

随机推荐