Angular-cli use proxy with dynamic port passed as a command-line argument

Viewed 1477

I am using angular-cli and to properly forward my requests to my backend using proxy I use the following config (proxy-config.json):

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

I serve the files using ng serve --proxy-config proxy-config.json

This works as expected, however I am using many different branches on different ports for testing purposes and I want to be able to easily change the backend port (in this case 1234) to something else without editing the file every time.

In an angularjs project with grunt I did something like grunt serve:dev -r 1234 where -r meant the proxy port.

1 Answers

you can pass a script instead of json as proxy.conf.js;

//can be right next to angular.json
var process = require("process")
var BACKEND_PORT = process.env.BACKEND_PORT || 8080
console.log('backend port: ' + BACKEND_PORT)
const PROXY_CONFIG = {
  "/api/*": {
    "target": "http://localhost:" + BACKEND_PORT + "/api/",
    "changeOrigin": true,
    "logLevel": "debug"
  }
}
module.exports = PROXY_CONFIG

To parametrize environment, you could call with something like;

ng serve ----configuration=confname #for instance production

which tells angular to load configurations from projectname.architect.serve.configurations.confname field inside angular.json. So you need to define it like;

...{
  ...
  "projects": {
    "projectname": {
      ...
      "serve": {
        ...
        "configurations": {
          "confname": {
            "BACKEND_PORT": 80
          }
        },
        ...
      },
      ...
    }
  }

Related