Angular-cli use proxy with dynamic port passed as command line argument
I am using angular-cli and correctly redirect my requests to my backend using a proxy. I am using the following config (proxy-config.json):
{
"/api/*": {
"target": "http://mybackend.com:1234",
"changeOrigin": true,
"secure": false,
"logLevel": "debug"
}
}
I serve files with 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 having to edit the file every time.
In angularjs project with grunt I did something like grunt serve:dev -r 1234
where -r meant proxy port.
source to share
you can pass 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 parameterize the environment, you can call with something like;
ng serve ----configuration=confname #for instance production
which tells angular to load configurations from the projectname.architect.serve.configurations.confname field inside angular.json. So you need to define it as;
...{
...
"projects": {
"projectname": {
...
"serve": {
...
"configurations": {
"confname": {
"BACKEND_PORT": 80
}
},
...
},
...
}
}
source to share