node.js - 后端和前端在不同端口上运行,CORS 错误

标签 node.js vue.js cors

我在不同的端口 (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/

相关文章:

javascript - 如何在 nodeJS 中将返回字节数组的 Bigtable HBase API 转换为整数或 float ?

javascript - VueJs : Focus on Input using v-el Directive inside v-repeat Directive

javascript - 根据 vueJS 中的 url id 过滤表数据

javascript - Python Tornado : how do I set WebSocket headers?

javascript - node js - 从回调中获取结果

javascript - 当模式中的验证匹配 false 时,Mongoose 不会抛出错误

laravel - 在 Laravel 中使用 VueJs 构建工具

angular - 如何使用 Firebase 托管的 webapp 获取没有 CORS header 的外部数据?

javascript - 对同一域发出 CORS 错误的获取请求

node.js - 在 React/Node/Mongo/Mongoose 应用程序中使用日期的最佳解决方案