Angular Proxy.Conf.Json 不适用于多个 api

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

我有以下 proxy.conf.json、日志行和 api 调用。

  {
  "/first/api/": {
    "target": "/first/api/",
    "secure": false,
    "logLevel": "debug"
  },
  "/second/api/": {
    "target": "/second/api/",
    "secure": false,
    "logLevel": "debug"
  }


[HPM] GET /first/api/values-> /first/api/
[HPM] GET /second/api/dummy -> /second/api/

return this.http.get<any>(this.firstApi + 'values')
return this.http.get<any>(this.secondApi + 'dummy')

鉴于我可以看到日志行,我相信 proxy.conf.json 已正确接收 api 调用,但当调用结束时我收到 404。日志只输出目标,所以我不清楚如何编写我需要的url,例如: localhost/first/api/values

当只有一个 api 时,这可以正常工作:

  {
  "/api/": {
    "target": "/first/",
    "secure": false
  }

任何人都可以建议我进一步的调试步骤吗?


已解决

yanky_cranky 的回答是正确的。作为理解他的答案与我所看到的内容有何关联的助手,我还需要查看我的 IIS 日志。在这里我可以看到正在调用哪些网址。

angular angular-cli
2个回答
12
投票

首先,这里你没有正确利用 Angular 的代理概念。

1) 关于代理:代理可用于将任何请求(如“/first/api”)映射到您无法访问的特定“域”。 如果 api 不是公开的,如果 api 指向不同的主机,则会导致 cors 问题(这是浏览器的属性):{即,主机名或端口或两者都不同} 借助 Angular,在我们的开发阶段,我们可以利用 Nginix 提供的相同反向代理概念并定位到正确的域。

有关代理的更多信息请点击这里

2) 你的 Nginix 配置将导致: 以下路径:

  {
  "/first/api/": {
    "target": "/first/api/",  
    "secure": false,
    "logLevel": "debug"
  },

/first/api/first/api/ ,因此你得到 404

  "/second/api/": {
    "target": "/second/api/",
    "secure": false,
    "logLevel": "debug"
  }

/秒/api/秒/api/,相同404

3)正确配置

 {
  "/first/api/": {

    "target": "http://localhost:{portNo}",

    "secure": false,

    "logLevel": "debug"

  },
  "/second/api/": {

    "target": "http://localhost:{portNo}",

    "secure": false,

    "logLevel": "debug"

  }

这些 api 将面向:

http://localhost:{portNo}/first/api

http://localhost:{端口号}/秒/api

干杯(y)


0
投票

如果您的上下文根相同,那么您也可以像下面这样使用,但是如果您对每个端点有不同的目标,那么您可以按照上面的建议来实现。

{
  "/**": {

    "target": "http://localhost:{portNo}",

    "secure": false,

    "logLevel": "debug"

  }
}

© www.soinside.com 2019 - 2024. All rights reserved.