【问题标题】:Angular Proxy.Conf.Json not working against multiple apisAngular Proxy.Conf.Json 不适用于多个 API
【发布时间】:2019-10-23 03:26:59
【问题描述】:

我有以下 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_craky 的回答是正确的。作为了解他的答案与我所看到的内容有何关联的助手,我还需要查看我的 IIS 日志。在这里我可以看到正在调用的 url。

【问题讨论】:

    标签: angular angular-cli


    【解决方案1】:

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

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

    More On Proxy Here

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

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

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

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

    /second/api/second/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:{portNo}/second/api

    干杯(y)

    【讨论】:

    • 这是一个很好的答案,但是我将如何为 Twitter api 添加一个配置,即api.twitter.com 问题是我不知道路径部分要使用什么。到目前为止,我已经完成了 {“api.twitter.com“: {“target”:”api.twitter.com”,”secure”:true,”changeOrigin”:true}} 恐怕 SO 正在从 Twitter URL 中删除 https 部分。请您想象一下 json 中的两个值都存在 https 协议。
    猜你喜欢
    • 2017-12-26
    • 2021-09-28
    • 2017-11-10
    • 2021-11-08
    • 2015-08-07
    • 2020-07-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多