如何在Angular CLI中配置代理

Eri*_*and 3 proxy node.js webpack angular-cli angular

我创建了一个新的@ angular/cli项目,并在根组件中添加了一个http GET调用.不使用代理,这工作正常.

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));
  }
}
Run Code Online (Sandbox Code Playgroud)

当我尝试在Angular CLI wiki中添加configure as describe时出错了.

我的proxy.conf.json文件:

{
  "/api": {
    "target": "https://dog.ceo",
    "secure": false
  }
}
Run Code Online (Sandbox Code Playgroud)

我将组件中的URL更改为/api/breeds/list/all.我跑了ng serve --proxy-config proxy.conf.json

然后我在浏览器控制台中发出内部服务器错误消息.在我开始服务的终端中,我收到了这条消息[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)

我已经尝试了其他几个配置选项和多个API.结果相似.

完整的代码可以在GitHub上找到:https://github.com/ErikNijland/angular-cli-proxy-test

使用的版本:

  • @ angular/cli:1.3.0
  • NodeJS:v8.1.4

注意:我知道@ angular/cli正在使用Webpack.反过来又使用http-proxy-middleware.

Mau*_*ana 5

我认为它正在发生,因为你要求https形式http的起源.这可以使用代理中的标志来解决.

{
    "/api": {
    "target": "https://dog.ceo",
    "secure": false,
    "changeOrigin": true
    }
}
Run Code Online (Sandbox Code Playgroud)