【问题标题】:How to enable CORS in express server?如何在 express 服务器中启用 CORS?
【发布时间】:2019-12-24 17:12:31
【问题描述】:

我有带有客户端的 MEAN 堆栈应用程序(端口 4200 上的实时服务器)并在端口 5000 上侦听快速服务器。现在我已经安装了 CORS 并启用了它,但是每次客户端发出 POST/GET 请求时,它都会以被屏蔽了。

客户:

  uri = 'http://localhost:5000/api';
  login (user) {
  return this.http.post(`${this.uri}/login`, user,{withCredentials: true});               
}

服务器:

  const cors = require('cors');
  app.use(cors({origin:["localhost:4200"], credentials: true}))

错误信息:

Access to XMLHttpRequest at 'http://localhost:5000/api/login' from origin 'http://localhost:4200' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

【问题讨论】:

    标签: angular express cors


    【解决方案1】:

    来自cors 包文档:

    “某些 CORS 请求被认为是‘复杂的’,需要初始 OPTIONS 请求(称为“飞行前请求”)。‘复杂’CORS 请求的一个示例是使用 HTTP 动词而非 GET/HEAD 的请求/POST(例如 DELETE)或使用自定义标头。要启用预飞行,您必须为要支持的路由添加新的 OPTIONS 处理程序。”

    如果你想使用 cors 包,你需要为任何需要的路由添加一个 OPTIONS 处理程序(即浏览器将调用的任何路由)。否则,您可以通过将所需的标头添加到请求中来手动处理应用范围的 CORS。

    【讨论】:

      猜你喜欢
      • 2019-08-14
      • 2021-11-18
      • 2020-11-21
      • 1970-01-01
      • 1970-01-01
      • 2017-02-20
      • 2018-01-30
      • 2018-02-09
      • 1970-01-01
      相关资源
      最近更新 更多