通过代理重定向Angular2 http请求 [英] Redirect Angular2 http requests through proxy
问题描述
我正在使用 angular-cli 引导程序创建Angular2应用程序,并将webpack-dev-server
用于调试目的.
I'm creating Angular2 application using angular-cli bootstrapper and use webpack-dev-server
for debugging purposes.
对于某些类型的http请求,我想使用webpack-dev-server 代理支持.
For some kinds of http request I want to redirect them to another backend using webpack-dev-server proxy support.
由于这个原因,我创建了proxy.conf.json
文件:
For this reason I've created proxy.conf.json
file:
{
"/api/**": {
"target": "http://localhost:4201",
"secure": false
}
}
并映射angular cli以使用此配置文件:
And map angular cli to use this config file:
ng serve --proxy-config proxy.conf.json
启动控制台消息后,通知我代理已成功创建:
After starting console message notifies me that proxy created successfully:
NG Live Development Server在 http://localhost:4200
已创建代理:/api/**-> http://localhost:4201
Proxy created: /api/** -> http://localhost:4201
但是来自http://localhost:4200/api/users
的所有请求始终返回404状态代码.我尝试了许多映射网址的示例,但没有帮助:
But all request from http://localhost:4200/api/users
always returns with 404 status code. I tried many examples of mapping urls but nothing helps:
"/api/users" -> "http://localhost:4201/users"
"/api/" -> "http://localhost:4201/"
我的代理服务器中的数据正在成功请求.我在做什么错了?
Data from my proxied server are requesting successfully. What I am doing wrong?
推荐答案
我找到了解决方案.我已经创建了简单的快速服务器来记录从代理服务器传输的所有请求,以检查映射的工作方式.我发现我对映射有错误的理解.
I found solution. I've created simple express server to log all requests transferred from proxy server to inspect how mapping works. And I found out that I had wrong understanding about mapping.
不是在配置文件中定义严格的映射:
Instead of strict mapping defined in config file:
/api/users => http://localhost:4201/users
使用下一条规则的webpack代理服务器映射:
webpack proxy server map using next rule:
/api/users => http://localhost:4201/users/api/users
所以这里的解决方案是添加pathRewrite
参数以排除前缀
So solution here is to add pathRewrite
parameter to exclude prefix
{
"/api/users": {
"target": "http://localhost:4201",
"secure": false,
"pathRewrite": {"^/api" : ""}
}
}
这篇关于通过代理重定向Angular2 http请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!