Various environment-based proxy settings in Angular 2 CLI

How can I declare 2 different proxy URLs for a development and production environment in an Angular 2 CLI project? For example, in development mode, I would like to use

{
    "/api/*": {
        "target": "http://localhost:3000",
        "secure": false
    }
}

but in production mode I will use

{
    "/api/*": {
        "target": "http://api.exampledomain.com",
        "secure": false
    }
}
+4
source share
2 answers

I do not think that you can control the proxy function through environment files. An alternative would be to define your api domains in your environment files

// environment.ts
export const environment = {
    production: false,
    api: 'http://localhost:3000'
};

// environment.prod.ts
export const environment = {
    production: true,
    api: 'http://api.exampledomain.com'
}

then in the ts source files pull the domain from the environment file

// some service
import { Injectable } from '@angular/core';
import { environment } from '../../../environment.ts';
import { Http } from '@angular/http';

@Injectable()
export class SomeService {
    constructor(private http: Http);

    getData(){
        return this.http.get(environment.api + '/rest-of-api');
    }
}

now when you run build or maintenance commands, they will use the api path defined in the environment file

0
source

In fact, you can do this, you just need to configure the router:

{
    "/api": {
        "target": "https://api.exampledomain.com",
        "secure": false,
        "logLevel": "debug",
        "router": {
          "localhost:4200" : "http://localhost:3000/exampledomain",
          "staging.exampledomain.com" : "http://api.staging.exampledomain.com"
        }
    }
}

What does it do:

  • URL-, = > ,
  • URL- = >

:

localhost: 4200 angular url "api/callMeMaybe", " http://localhost:3000/exampledomain".
staging.exampledomain.com, http://api.stagging.exampledomain.com.
, , .

, (1- )

example

"Chrome debugger Network" api, : api call header screenshot

0

Source: https://habr.com/ru/post/1683075/


All Articles