Use Angular CLI with api on two different ports

Recently, I met a problem:

During development, how to use Angular CLI (default port 4200) with an API (port 8080, with NodeJS/Express for me)

I suppose that you already discovered as well that you cannot run easily two applications on the same port...
Moreover, if you are trying to contact an API outside of the same domain name, you will have CORS troubles...

XMLHttpRequest cannot load http://localhost:8080/api/stats/nru/appro/instructor. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:4200' is therefore not allowed access.

According to my research the best solution is to use the proxy feature of the Angular CLI tool.

My example case:

  • Angular app is running on port 4200
  • My API is running on port 8080 and is propulsed thanks to NodeJS and expressJS

How to configure it?

  • Create a proxy.conf.json file with the following content:
{
  "/api": {
    "target": "http://localhost:8080",
    "secure": false
  }
}
  • Inside your Angular app: do not precise anymore the absolute path to your API and just use

api/...

Example of API call:

return this.http.post('api/hello', {'name': 'spywen'}, this.options)  
            .map((response: Response) => <string[]>response.json())
            .catch(this.handleError);
  • Run your app with the command:

ng serve --proxy-config proxy.conf.json