I need to create a proxy to my backend server in order to communicate with it. I've already succesfully set this up, but now I have 2 places where I need to change variables when changing the environment.
My versions:
7.0.6
7.1.0
NOTE: I have the proxy working (see Angular docs for the setup), I only want to improve the setup.
Proxy.conf.js
This is my current (and working!) config.js
const PROXY_CONFIG = {
"/api/*": {
"target": "https://url.to.somewhere/",
"logLevel": "debug",
"changeOrigin": true
}
};
module.exports = PROXY_CONFIG;
What I would like it to combine this file with the Angular environment.ts file.
What I want
I would like to use the variables from the environment.ts file to configure the proxy, so I would only have to maintain my environment.ts instead of both files (also the proxy.conf.js).
Something along the lines of this:
import {env} from 'environments/environment';
const root = env.BASE_SUFFIX + '/*'; // BASE_SUFFIX = '/api'
function getConfig() {
const PROXY_CONFIG = {};
PROXY_CONFIG[root] = {
target: env.API_URL, // API_URL = https://url.to.somewhere/
logLevel: "debug",
changeOrigin: true,
};
return PROXY_CONFIG;
}
module.exports = getConfig();
The problem I currently run into is that environment.ts is a Typescript file and cannot be correctly included by the javascript, because I have some import {foo} from 'bar'
in my environment.ts file.
So const env = require(environments/environment.ts).env
is not working, due to the ES6 imports.
Any suggestions on how I should do this or is this not possible and should I just use 2 separate files?
angular provide environments to configure variables for local, staging and production. angular predefine environment configuration we can use to local and production variable dynamically.
process. env is available to Node applications, which an Angular application is not. You have several options: Make a task of some sort in your build pipeline to update the environment file with the correct value if it truly needs to be dynamic.
While developing an Angular app with Angular CLI, it's not very easy to integrate the dotenv package. After a few hours of research, I found a process that works well enough. Most Node developers use dotenv as a way to manage private API keys.
I'm using it this way. you can try this
// create proxy.conf.json
{
"/api/*": {
"target": "http://localhost:8000",
"secure": false,
"logLevel": "debug",
"changeOrigin": true
}
}
// in package.json file "scripts" under that find "start"
"start": "ng serve --proxy-config proxy.conf.json",
// api call
this.http.post('/api/api_name/')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With