如何在Angular中使用代理?

How to use proxy in Angular?

我有 Angular 个具有此设置的代理:

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

所以,我已经将所有请求绑定到服务器,从 http://localhost:4200http://localhost 没有端口 4200。

为什么它对我不起作用?

命令是:

ng serve --proxy-config

您的配置将代理:

from: http://localhost:4200/api
  to: http://localhost:4200/

因此该代理在 Angular 之外工作,您可以这样称呼它 URL:

httpClient.get("http://localhost:4200/api")

以上实际上会调用 http://localhost:4200/。我们可以将其缩短为 httpClient.get("/api") 的调用,因为我们处于相同的 domain:port

So, I have tied to proxy all request to server from http://localhost:4200 to http://localhost without port 4200.

您需要一个不同的代理 URL

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

以上配置将代理:

from: http://localhost:4200/api
  to: http://localhost/

/apipathRewrite 规则从代理重写中删除。

您仍然会调用 httpClient.get("/api") 来命中目标代理。

在此处查看文档:

https://github.com/angular/angular-cli/blob/master/docs/documentation/stories/proxy.md

尝试将标签 "/ api /" 更改为 "/ api / *""target": "[http: // localhost: 4200] (http: // localhost: 4200)"

确保你的 package.json

中有这个
{
  ...
  "scripts": {
    ...
    "start": "ng serve -o --proxy-config proxy.conf.json",
    ...
  },
  ...
}