Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

angular

build

i am using proxy api setting for API calls in angular 5 as discussed in this website .https://juristr.com/blog/2016/11/configure-proxy-api-angular-cli/ this working properly when i use npm start. but when i build this and host it on IIS. it is not working. i believe proxy.config.json is not added inside dist folder.

like image 571
Arul Avatar asked Feb 22 '18 06:02

Arul


3 Answers

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/
}
like image 168
Tawatchai Phetdumrongsakul Avatar answered Oct 18 '22 05:10

Tawatchai Phetdumrongsakul


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 }, ...
]
...
like image 43
Mixalloff Avatar answered Oct 18 '22 05:10

Mixalloff


This configuration is ONLY for your development setup and should not be used in production. You need to include other solutions for your production environment to run.

like image 40
Gaurav Rao Avatar answered Oct 18 '22 05:10

Gaurav Rao