【问题标题】:angular proxy config not working角度代理配置不起作用
【发布时间】:2018-08-04 01:59:44
【问题描述】:

我不明白我哪里错了。

ps。已经尝试通过这个答案修复但仍然无法正常工作

Angular-CLI proxy to backend doesn't work

Configure Angular-cli proxy for custom headers in request to backend?

Angular-CLI proxy doesn't work

ng serve --proxy-config proxy.config.json

** Angular Live Development Server is listening on localhost:4200, open your browser on http://localhost:4200/ **
 10% building modules 3/3 modules 0 active[HPM] Proxy created: /api  ->  
http://localhost:1234
[HPM] Subscribed to http-proxy events:  [ 'error', 'close' ]

package.json

{
  "name": "budget",
  "version": "0.0.0",
  "scripts": {
   "ng": "ng",
  "start": "ng serve --proxy-config proxy.config.json",
  "build": "ng build --prod",
  "test": "ng test",
  "lint": "ng lint",
  "e2e": "ng e2e"
},

proxy.config.json

{
  "/api": {
  "target": "http://localhost:1234",
  "secure": false,
  "changeOrigin": true,
  "logLevel": "debug"
  }
}

Angular CLI:6.1.2

节点:10.8.0

操作系统:darwin x64

角度:6.1.1

npm -v 6.2.0

【问题讨论】:

    标签: angular npm


    【解决方案1】:

    您仅匹配 /api 网址。如果您想匹配以/api 开头但有其他内容的网址,请使用/api/*

    proxy.config.json

    {
      "/api/*": {
        "target": "http://localhost:1234",
        "secure": false,
        "changeOrigin": true,
        "logLevel": "debug"
      }
    }
    

    说明

    此配置将从本地服务器(假设它是 localhost:4200)代理到您的目标,所以:

    • localhost:4200/api --> http://localhost:1234/api
    • localhost:4200/api/product --> http://localhost:1234/api/product
    • localhost:4200 --> 没有代理
    • localhost:4200/whatever --> 没有代理

    如果要从目标路由中排除/api/,请在proxy.config.json 中包含pathRewrite

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

    【讨论】:

      【解决方案2】:

      改变

      {
        "/api": {
        "target": "http://localhost:1234",
        "secure": false,
        "changeOrigin": true,
        "logLevel": "debug"
        }
      }
      

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-07-19
        • 2018-08-20
        相关资源
        最近更新 更多