[英]Angular2/Angular seed http-proxy-middleware proxy api requests
[英]Redirect Angular2 http requests through proxy
我正在使用angular-cli bootstrapper創建Angular2應用程序,並使用webpack-dev-server
進行調試。
對於某些類型的http請求,我想使用webpack-dev-server 代理支持將其重定向到另一個后端。
因此,我創建了proxy.conf.json
文件:
{
"/api/**": {
"target": "http://localhost:4201",
"secure": false
}
}
並映射angular cli以使用此配置文件:
ng serve --proxy-config proxy.conf.json
啟動控制台消息后,通知我代理已成功創建:
NG Live Development Server在http:// localhost:4200上運行
創建的代理:/ api / **-> http:// localhost:4201
但是所有來自http://localhost:4200/api/users
請求始終返回404狀態代碼。 我嘗試了許多映射網址的示例,但沒有幫助:
"/api/users" -> "http://localhost:4201/users"
"/api/" -> "http://localhost:4201/"
來自代理服務器的數據正在成功請求。 我做錯了什么?
我找到了解決方案。 我已經創建了簡單的快速服務器來記錄從代理服務器傳輸的所有請求,以檢查映射的工作方式。 我發現我對映射的理解有誤。
代替在配置文件中定義的嚴格映射:
/api/users => http://localhost:4201/users
使用以下規則的webpack代理服務器映射:
/api/users => http://localhost:4201/users/api/users
所以這里的解決方案是添加pathRewrite
參數以排除前綴
{
"/api/users": {
"target": "http://localhost:4201",
"secure": false,
"pathRewrite": {"^/api" : ""}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.