Erik Nijland Erik Nijland -3 years ago 566
Node.js Question

How to configure a proxy in Angular CLI

I created a new @angular/cli project and added one http GET call in the root component. Without using a proxy this works fine.

export class AppComponent implements OnInit {
constructor(private http: Http) {}

ngOnInit() {
this.http
.get('https://dog.ceo/api/breeds/list/all')
.map(response => response.json())
.subscribe(data => console.log(data));
}
}


When I try to add the configure as describe in the Angular CLI wiki things go wrong.

My proxy.conf.json file:

{
"/api": {
"target": "https://dog.ceo",
"secure": false
}
}


I changed the URL in the component to
/api/breeds/list/all
. And I ran
ng serve --proxy-config proxy.conf.json


Then I'm gertting Internal Server Error message in my browsers console. And in the terminal where I started ng serve I'm getting this message
[HPM] Error occurred while trying to proxy request /api/breeds/list/all from localhost:4200 to https://dog.ceo (EPROTO)
(https://nodejs.org/api/errors.html#errors_common_system_errors)


I have tried several other configuration options and multiple API's. Results are similar.

The complete code is available on GitHub: https://github.com/ErikNijland/angular-cli-proxy-test

Versions used:


  • @angular/cli: 1.3.0

  • NodeJS: v8.1.4



Note: I understand that @angular/cli is using Webpack. Which in turn is using http-proxy-middleware.

Answer Source

I think it is happening because of the origin your are asking https form http. This can be solved using a flag in your proxy.

{
    "/api": {
    "target": "https://dog.ceo",
    "secure": false,
    "changeOrigin": true
    }
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download