跨源请求被阻止的 CORS - 使用 angular cli 解决 [Dev only]

Cross Origin Request Blocked CORS - solving with angular cli [Dev only]

最近我遇到了以下错误:

Access to XMLHttpRequest at 'localhost:8080/api/xyz' 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.

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

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

首先我的设置: Angular7、使用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>;
  }
}

记住:此答案仅供开发使用

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

所以localhost:4200localhost:8080

不是同一个来源

Using a proxy is probably the easiest way to solve this

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" ~> ""