【问题标题】:Backend and Frontend running on different port, CORS error后端和前端在不同的端口上运行,CORS 错误
【发布时间】:2019-06-29 02:01:46
【问题描述】:

我在不同的端口 (8000,8001) 上运行后端和前端,我无法从 express 服务器进行 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 错误阻止。

【问题讨论】:

  • 我好几天都找不到这个问题的任何答案,它们将被部署在不同的端口中,所以合并不是一种选择。如果有人给我任何建议,那将是一个巨大的帮助!谢谢!

标签: node.js vue.js cors


【解决方案1】:

要解决浏览器中的 CORS 错误,您应该在响应中添加以下 HTTP 标头:

Access-Control-Allow-Headers: Content-Type

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

app.use(cors({
  'allowedHeaders': ['Content-Type'],
  'origin': '*',
  'preflightContinue': true
}));

【讨论】:

  • cors() 已经在服务器端启用,它允许我的前端发出 html api 请求。我认为这可以完成工作。现在的问题是 CORS 阻止我的服务器重定向我的前端.. 会放标头帮助吗?因为前端想要阻止来自不同来源的重定向,我可以绕过从服务器端添加标头吗?
  • 如果是这样的话,CORS 就变得毫无意义了。
  • 我已经使用代码 sn-p 编辑了答案,您应该添加以解决问题。让我们从这个开始,看看是否有任何额外的错误
  • 感谢您的快速回复。我应用了代码,但什么也没发生。它仍然有相同的错误消息。
  • 嗯也许可以尝试添加 preflightContinue: true (添加到答案中)
【解决方案2】:

使用 CORS 中间件,例如

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, token, Content-Length, X-Requested-With, *');
  if ('OPTIONS' === req.method) {
    res.sendStatus(200);
  } else {
    next();
  }
};
app.all("/*", 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, token, Content-Length, X-Requested-With, *');
  next();
});
app.use(enableCORS);

【讨论】:

    【解决方案3】:

    就我的两分钱...


    如果您正在处理身份验证调用并为此使用 cookie,则应配置 CORS。为此,您必须记住:
    1. 允许前端为AllowedOrigin
    2. allowCredentials 设置为true
    3. 不要AllowedOrigin 使用通配符 (*)(同样,如果您正在处理 cookie/身份验证)。使用protocolhostport [Why]

    Golang 示例(使用 gorilla/handlers):

    handlers.CORS(
        // allowCredentials = true
        handlers.AllowCredentials(),
        // Not using TLS, localhost, port 8080 
        handlers.AllowedOrigins([]string{"http://localhost:8080"}),
        handlers.AllowedMethods([]string{"GET", "POST", "PUT", "HEAD", "OPTIONS"}),
        handlers.AllowedHeaders([]string{"X-Requested-With", "Content-Type", "Authorization"}),
    )
    

    【讨论】:

      【解决方案4】:

      所以我一直在不同端口上的后端和前端遇到这个问题并阻止彼此的请求。
      对我有用的解决方案是设置前端代理到后端:Medium article

      待办事项:将"proxy":<backend_server_link> 添加到前端文件夹的package.json

      【讨论】:

        猜你喜欢
        • 2023-04-07
        • 2018-09-21
        • 2021-06-16
        • 1970-01-01
        • 2021-04-22
        • 2021-12-16
        • 1970-01-01
        • 2017-09-27
        • 2020-11-05
        相关资源
        最近更新 更多