如何在Angular中使用代理?

问题描述 投票:0回答:2

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

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

因此,我将所有从服务器的请求从http://localhost:4200代理到http://localhost都绑定到了端口4200。

为什么对我不起作用?

命令是:

ng serve --proxy-config
angular angular6 angular8
2个回答
1
投票

您的配置将代理:

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

因此,我将所有从服务器的请求从http://localhost:4200代理到http://localhost都绑定到了端口4200。

您将需要其他代理URL

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

以上配置将代理:

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

/api通过pathRewrite规则从代理重写中删除。

您仍然会呼叫httpClient.get("/api")来击中目标代理。

请参阅此处的文档:

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


1
投票

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

确保您的package.json中有此文件

{
  ...
  "scripts": {
    ...
    "start": "ng serve -o --proxy-config proxy.conf.json",
    ...
  },
  ...
}
© www.soinside.com 2019 - 2024. All rights reserved.