proxy.config.json is not working in Angular 4/5 when i use ng build

I am facing the same problem with you. My proxy.config.json has worked in my dev environment but does not work in PROD environment even I built with build --prod

After finding a way, I found a solution to make proxy backend with middleware instead (I used Nginx in my case).

If you also used Nginx, you can do proxy backend by configure this into your nginx configuration.

nginx.conf

location /api/ {
  proxy_pass      http://127.0.0.1:8087; 
  #all incoming http request with /api/ will be forwarded to http://127.0.0.1:8087/api/
}

Proxy is working when dev server active. ng build doesn't start dev server, this command only build the project. Therefore you cannot use proxy in assembled project. You can use smth like ng serve --proxy-config proxy.config.json --prod for testing in prod environment with proxy

If you need to use another base url in production, you can use HttpInterceptor. Just create service like this

@Injectable()
export class InterceptorsService implements HttpInterceptor {

    intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
      const proxyReq = req.clone({ url: `${ BASE_PATH }${ request.url }` });
      return next.handle(proxyReq);
    }
}

and add it to providers in your module

...
providers: [
    { provide: HTTP_INTERCEPTORS, useClass: InterceptorsService, multi: true }, ...
]
...

Tags:

Build

Angular