How to Deploy Angular app with Proxy Settings

前端 未结 3 2096
春和景丽
春和景丽 2021-02-13 21:49

I have a proxy config file which has API(web service) link to target to make calls to our database. This proxy config is working fine locally using npm start .<

3条回答
  •  误落风尘
    2021-02-13 22:28

    To deploy an Angular 8 application to production

    You can use the environments feature, for example:

    For Development

    proxy.conf.json

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

    You set the backend baseURL in environments/environment.ts

    export const environment = {
      production: false,
      backend: {
        baseURL:"http://localhost:3000/api"
      }
    };
    

    In the service the baseURL is used:

      baseUrl: string = environment.backend.baseURL;
    
      getAll(): Observable {
        return Observable.create(observer => {
         this.http.get(`${this.baseUrl}` + '/users')
            .subscribe((result) => {
              const accountsResponse = result;
              observer.next(accountsResponse);
              observer.complete();
            });
        });
      }
    

    For development the live serve is used:

    $ng serve --proxy-config proxy.conf.json  --host 0.0.0.0 --port 4200
    

    The url for development:

    http://localhost:4200/yourapp
    

    The running serve will enable CORS and send the API calls to

    http://localhost:3000/api/v1
    

    For Deployment to production

    The command to build for production:

    $ng build --prod --base-href=/yourapp/
    

    The service will take the baseURL from prod environment configuration:

    environments/environment.prod.ts

    export const environment = {
      production: true,
      backend: {
        baseURL:"http://example.com/api"
      }
    };
    

    So, by using different environments, you can configure different api urls. Remember to enable CORS in your production web server, by default the browser does not allow to connect to a different domain than the one serving your Angular app.

提交回复
热议问题