Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 940
Erik Nijland Avatar asked Aug 15 '17 19:08

Erik Nijland


1 Answers

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

{
    "/api": {
    "target": "https://dog.ceo",
    "secure": false,
    "changeOrigin": true
    }
}
like image 172
Mauricio De La Quintana Avatar answered Sep 20 '22 02:09

Mauricio De La Quintana