[英]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.我创建了一个新的 @angular/cli 项目并在根组件中添加了一个 http GET 调用。 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.当我尝试按照Angular CLI wiki中的描述添加配置时,出现问题。
My proxy.conf.json file:我的 proxy.conf.json 文件:
{
"/api": {
"target": "https://dog.ceo",
"secure": false
}
}
I changed the URL in the component to /api/breeds/list/all
.我将组件中的 URL 更改为
/api/breeds/list/all
。 And I ran ng serve --proxy-config proxy.conf.json
我跑了
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)
在我开始 ng serve 的终端中,我收到此消息
[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.我尝试了其他几个配置选项和多个 API。 Results are similar.
结果相似。
The complete code is available on GitHub: https://github.com/ErikNijland/angular-cli-proxy-test完整代码可在 GitHub 上获得: https ://github.com/ErikNijland/angular-cli-proxy-test
Versions used:使用的版本:
Note: I understand that @angular/cli is using Webpack.注意:我知道 @angular/cli 正在使用 Webpack。 Which in turn is using http-proxy-middleware.
这反过来又使用了 http-proxy-middleware。
I think it is happening because of the origin your are asking https from http.我认为这是因为您从 http 询问 https 的来源。 This can be solved using a flag in your proxy.
这可以使用代理中的标志来解决。
{
"/api": {
"target": "https://dog.ceo",
"secure": false,
"changeOrigin": true
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.