2017-08-15 64 views
2

我創建了一個新的@ angular/cli項目,並在根組件中添加了一個http GET調用。沒有使用代理,這工作正常。如何在Angular CLI中配置代理

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

然後我在我的瀏覽器控制檯中發出內部服務器錯誤消息。並且在我開始服務的終端中,我收到此消息[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

版本:

  • @角/ CLI:1.3.0
  • 的NodeJS:V8.1.4

注意:我知道@ angular/cli正在使用Webpack。而後者又使用http-proxy-middleware。

+1

'EPROTO'聞起來像一個協議問題。也許是因爲你通過https請求,但將'secure'設置爲false?協議之間必須存在不匹配的地方。 – jackarms

回答

2

我認爲這是因爲你問的https格式http的原點。這可以使用代理中的標誌來解決。

{ 
    "/api": { 
    "target": "https://dog.ceo", 
    "secure": false, 
    "changeOrigin": true 
    } 
} 
+0

謝謝!現在正在工作。我總是儘管那個起源只是主人。顯然它是計劃+主機+端口... –