4371

Angular CLI - Set Up production proxy for now deploying

I am currently using now.sh for deploying my app. Recently, I decided to move the baseUrl for requests to a proxy.config.json file.

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

For deploying with now.sh I change the scripts in package.json to:

"start": "serve dist/ --single", "build": "ng build --prod",

so, first, I did a ng build.

The thing is, I'm needing a different target for proxy.config.json, because I deployed an API and I want to use it in the production app

I was thinking on having two files proxy.config.dev.json and proxy.config.prod.json, but I don't know if I can target a different proxy with the cli. The problem is that I'm using serve for production and not ng serve so proxy-config is not available.

What do you suggest? How can I get to work it?

Answer1:

I have realized that is a better solution to use "environments" which came by default with angular-cli.

So I setup a baseUrl in both environments {dev, prod}. And then the builds will not change. Then you have to modify your services to use this env variable.

Answer2:

ng serve uses the angular cli which accepts a parameter for a proxy file config (details here: https://github.com/angular/angular-cli/wiki/serve) . the 'serve' command you're using in production is another package (I assume this one https://www.npmjs.com/package/serve) which doesn't support the same feature set. You need to a web server that supports proxying (e.g. nginx appears to as detailed here http://nginx.org/en/docs/beginners_guide.html#proxy) OR else a standalone solution for the proxy feature that complements popular http server packages like 'serve', 'http-server', 'lite-server' e.g. some network appliances can help as well. If you / anyone else finds other good options for hosting angular apps w/ a proxy please do share as I'm looking to evaluate more options also.

Answer3:

Using Angular Interceptor and Angular cli way to set baseUrl as explained above and up voted for giving hint. In case someone looking for more info then following helps to move forward

`<pre> import { environment } from './../../environments/environment'; import { Injectable } from '@angular/core'; import { HttpInterceptor, HttpRequest, HttpHeaders, HttpHandler, HttpEvent, HttpEventType } from '@angular/common/http'; import { Observable } from 'rxjs/Observable'; import 'rxjs/add/operator/do'; @Injectable() export class WebApiBaseURLInterceptor implements HttpInterceptor { className = "WebApiBaseURLInterceptor"; constructor() { // add more http options here like OAuth2 access token const httpOptions = { headers: new HttpHeaders({ 'Content-Type': 'application/json' }) }; } /** * * @param {HttpRequest<any>} req * @param {HttpHandler} next * @returns {Observable<HttpEvent<any>>} */ intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> { //the baseURL set in environment folder which has both Dev and Prod const url = environment.baseUrl; req = req.clone({ url: url + req.url }); // return next.handle(req); // lets add elapse time difference const started = Date.now(); return next.handle(req).do(event => { if (event.type == HttpEventType.Response) { const elapsed = Date.now() - started; console.log(`${this.className}: Request for ${req.urlWithParams} took ${elapsed} ms.`); } }); } } </pre>`

Following is Dev environment folder and file so edit as below,

// The file contents for the current environment will overwrite these during build.

// The build system defaults to the dev environment which uses environment.ts, but if you do

// ng build --env=prod then environment.prod.ts will be used instead.

// The list of which env maps to which file can be found in .angular-cli.json.

`<pre> export const environment = { production: false, baseUrl: 'http://localhost:8080/' }; </pre>`

Recommend

  • ngImgCrop Dependency Injection not working properly in AngularJs
  • Deploying a NodeJS App to Azure Websites fails on installing NPM packages from pagages.json from dep
  • Unable to communicate to device with .local domain using android, corova-zeroconf-plugin
  • Update vsts-npm-auth with new username and password
  • What does the “?” mean in the following statement
  • eC (Ecere) how to not worry about private data fields of a class
  • SSRS 2008 - Sorting within a group
  • What's the name of this finding square root algorithm?
  • Where these are stored?
  • cordova is not defined - cordova.js has already been loaded :: Ionic
  • jQuery: add elements until a particular height is reached
  • Combining two different ActiveRecord collections into one
  • How to generate and display a QR Code in ionic 2
  • Unable to decode certificate at client new X509Certificate2()
  • Needing to do .toArray() to get output of mongodb .find() on key name not value
  • How to use carriage return with multiple line?
  • Installing Apache MyFaces 2 on WildFly 8.2.0
  • Hardware Accelerated Image Scaling in windows using C++
  • does jqgrid support a multiple checkbox list for editing
  • Installing Hadoop, Java Exception about illegal characters at index 7?
  • Master page gives error
  • Jenkins: How To Build multiple projects from a TFS repository?
  • Optimizing database types to compact database (SQLite)
  • RectangularRangeIndicator format like triangular using dojo
  • How do I fake an specific browser client when using Java's Net library?
  • Cross-Platform Protobuf Serialization
  • Shallow update not allowed (git > 1.9)
  • Can I make an Android app that runs a web view in Chrome 39?
  • Symfony2: How to get request parameter
  • Timeout for blocking function call, i.e., how to stop waiting for user input after X seconds?
  • ORA-29908: missing primary invocation for ancillary operator
  • Do I've to free mysql result after storing it?
  • Apache 2.4 - remove | delete | uninstall
  • Run Powershell script from inside other Powershell script with dynamic redirection to file
  • How do I rollback to a specific git commit
  • Matrix multiplication with MKL
  • How to include full .NET prerequisite for Wix Burn installer
  • Revoking OAuth Access Token Results in 404 Not Found
  • Turn off referential integrity in Derby? is it possible?
  • XCode 8, some methods disappeared ? ex: layoutAttributesClass() -> AnyClass