【问题标题】:Cross Origin Request Blocked CORS - solving with angular cli [Dev only] [duplicate]跨源请求被阻止的 CORS - 使用角度 cli 解决 [仅限开发人员] [重复]
【发布时间】:2019-08-07 23:19:20
【问题描述】:

最近遇到如下错误:

在 'localhost:8080/api/xyz' 从源访问 XMLHttpRequest 'http://localhost:4200' 已被 CORS 策略阻止:跨源 请求仅支持协议方案:http、data、chrome、 chrome 扩展,https。

Angular 为这个问题提供了一个简单的解决方案,但我花了足够多的时间才找到它。在 Angular 的文档中,我也没有找到任何关于 SO 的简单内容。

显然,这个错误与 Angular 完全无关。我相信几乎每个开发人员都会不时遇到这个错误,我想分享一个简单的解决方案,以便我们继续处理重要的事情。

首先我的设置: Angular 7,以及HttpClient的使用(doc)

我创建了一个小服务:

export class HelloServerService {
  private readonly rootApi: string = 'http://localhost:8080/api/';

  constructor(@Inject(HttpClient) private readonly http: HttpClient) {
  }

  public getHelloWorld(name: string): Observable<string> {
    return this.http.get(this.rootApi + name, {responseType: 'text', params: {}}) as Observable<string>;
  }
}

【问题讨论】:

  • private readonly rootApi: string = 'http://localhost:8080/api/'(你需要在请求URL中的'http://'协议部分)

标签: angular cors angular-cli cross-origin-read-blocking


【解决方案1】:

记住:此答案仅用于开发目的

首先,关键问题是较新的浏览器阻止了跨域请求,这也涉及到端口号的区分:

所以localhost:4200localhost:8080 的来源不同

使用代理可能是解决此问题的最简单方法

Angular CLI 能够轻松配置一个简单的代理,它将所有已定义的 api 调用委托给我们喜欢的目标。

This article from Richard Russell 描述了我们如何配置代理。

简而言之:

我们新建一个文件proxy.conf.json

{
  "/api": {
    "target": "http://localhost:8080",
    "secure": false,
    "logLevel": "debug",
    "pathRewrite": {
      "^/api": ""
    }
  }
}

将它添加到我们的 angular.json

 "serve": {
          "builder": "@angular-devkit/build-angular:dev-server",
          "options": {
            "browserTarget": "xyz:build",
            "proxyConfig": "proxy.conf.json"
          },

并通过 ng serve 运行它:

预期的输出:

** Angular Live Development Server is listening on localhost:4200, open your browser on http://localhost:4200/ **
[HPM] Proxy created: /api  ->  http://localhost:8080
[HPM] Proxy rewrite rule created: "^/api" ~> ""

【讨论】:

  • 代理是一个很好的方式,但它只是用于开发的临时方式。在现实世界中,如果您想将应用程序部署到真实服务器中,则必须在后端为前端源设置 CORS。那你为什么不现在设置呢?
  • 是的,我当然可以将此信息添加到答案和问题中
  • 嗨,澄清一下:如果我有多个端点(比如说localhost:8080/users,然后是localhost:8080/reviews),我是否必须为每个端点添加一个条目?这就是它的工作原理吗?
  • 谢谢你的答案。我做了你做的,但仍然有一个错误。我正在使用 Angular 9。这是来自 Chrome 的日志:Access to XMLHttpRequest at 'localhost:7777/api/register' from origin 'http://localhost:4200' has been blocked by CORS policy: Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https.
猜你喜欢
  • 2021-03-10
  • 2020-08-16
  • 2017-05-31
  • 1970-01-01
  • 1970-01-01
  • 2014-09-06
  • 2021-07-30
  • 2017-01-12
  • 2023-04-02
相关资源
最近更新 更多