我创建了一个新的 @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));
}
}
当我尝试按照 Angular CLI wiki 中的描述添加配置时,出现了问题。
我的 proxy.conf.json 文件:
{
"/api": {
"target": "https://dog.ceo",
"secure": false
}
}
我将组件中的 URL 更改为
/api/breeds/list/all
。我就跑了ng serve --proxy-config proxy.conf.json
然后我在浏览器控制台中收到内部服务器错误消息。在我启动 ngserve 的终端中,我收到此消息
[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正在使用Webpack。这又使用http-proxy-middleware。
我认为发生这种情况是因为您从 http 询问 https 的起源。这可以使用代理中的标志来解决。
{
"/api": {
"target": "https://dog.ceo",
"secure": false,
"changeOrigin": true
}
}
对我来说,以下方法有效:
{
"/api": {
"target": {
"host": "dog.ceo",
"protocol": "https:",
"port": 443
},
"secure": false,
"changeOrigin": true,
"logLevel": "info"
}
}
ng serve --proxy-config proxy.conf.json