角度代理配置不起作用

时间:2018-08-04 01:59:45

标签: angular npm

我不明白我在哪里错。

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

3 个答案:

答案 0 :(得分:0)

尝试以下操作

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

答案 1 :(得分:0)

更改

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

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

答案 2 :(得分:0)

您仅匹配/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/,请在pathRewrite的内部包括proxy.config.json

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