Friday, March 10, 2017

Angular CLI–Avoid CORS issues

By default when using ng-serve, webpack will serve your Angular 2 content from http://localhost:4200. However when your backend is hosted on a different URI(which probably is the case) you get CORS errors when you try to call your backend:

image

One solution is to configure CORS on your backend, but if you want to host your frontend code and the backend on the same URI in the end, I have an alternative for you…

Angular-CLI allows you to specify a proxy file. In this proxy file you can specify a URI pattern and webpack will proxy these requests to your backend.

Let’s see some code:

  • My Angular Component. To simplify the codebase I have put everything inside my component. A better way would be to embed the HTTP logic inside a service.
  • A proxy.config.json file. In this file I specify a URI pattern and the target URI.

To invoke the application we have to specify the proxy.config.json path when calling ng serve:

ng serve –proxy-config proxy.config.json

That’s it!

2 comments:

bonz said...

Hi thanks for the post but do I change the "localhost:7667 to my restapi's url? Sorry still a bit new to this.

Anonymous said...

Thank you, Helped me