angular proxy config not working

2020-05-09 15:42发布

问题:

i don't understand where i am wrong .

ps. already try to fix by this answer but still not working

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

Node: 10.8.0

OS: darwin x64

Angular: 6.1.1

npm -v 6.2.0

回答1:

change

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

to

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


回答2:

You're matching only /api url. If you want to match urls that begin with /api but have something else use /api/*.

proxy.config.json

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

Explanation

This configuration will proxy from local-server (lets suppose it is localhost:4200) to your target, so:

  • localhost:4200/api --> http://localhost:1234/api
  • localhost:4200/api/product --> http://localhost:1234/api/product
  • localhost:4200 --> no proxy
  • localhost:4200/whatever --> no proxy

If you want to exclude /api/ from the target route, include pathRewrite inside in proxy.config.json:

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


标签: angular npm