Angular4-5中代理服务器的实现 [英] Implementation of Proxy Server in Angular4-5
问题描述
问题陈述:使用angular-cli和Angular-5开发的Client/UI, UI 在 http://localhost:8000 ,这意味着所有api的调用方式如 http://localhost:8000/users/getuserinfo 并正确返回一些json数据.还具有其他路由,例如 http://localhost:8000/student/getresult 等.
Problem Statement: Client/UI developed using angular-cli and Angular-5, UI is running on http://localhost:4200 and we have back-end server running on http://localhost:8000 that means all api's called like http://localhost:8000/users/getuserinfo and returns some json data properly. Also having other routes like http://localhost:8000/student/getresult etc.
因此,当我运行ng serve
时,我必须为此创建代理,在 http://上的浏览器中打开应用程序localhost:4200 ,但同时调用api的url形式,例如 http://localhost:4200/users/getuserinfo ,它返回的结果类似于404,即未找到,但是当我在 http:的另一个选项卡中单击url时://localhost:8000/users/getuserinfo ,它会向我返回json数据.
So i have to create proxy for this as when i run ng serve
my application open-up in browser on http://localhost:4200, but while making call to api's url forms like http://localhost:4200/users/getuserinfo which return result like 404 i.e. not found, but when i hit url in another tab for http://localhost:8000/users/getuserinfo, it returns me json data.
所以我需要为 http://localhost:4200/users/getuserinfo 创建代理例如 http://localhost:8000/users/userinfo .我尝试使用 DOCS 实现,但未成功,也不知道如何在proxy.conf.json文件中获取所有api,有人可以帮我吗?
So i need to create proxy for http://localhost:4200/users/getuserinfo to like as http://localhost:8000/users/userinfo. I tried to implement using DOCS but not succeeded and also dont know how get all apis in proxy.conf.json file, can some one help me here?
下面是我的代码,
{
"/users/userinfo": {
"target": "http://localhost:8000",
"secure": false
}
}
推荐答案
为您的api定义代理文件,并使用以下命令启动服务器:
Define a proxy file for your api and start the server with this command:
ng serve --proxy-config proxy.conf.json
proxy.conf.json
proxy.conf.json
{
"/users": {
"target": "http://localhost:8000",
"secure": false
}
}
我发现用/api
为我的所有api路由添加前缀会更容易.这使在生产环境中提供应用程序时更加容易,因为您可以在所有不以/api
开头的路由上返回该应用程序,并且它使代理配置同样简单,因为您只需要设置一个规则,而不是可能的多个规则.使用当前策略.
I find that it is easier to prefix all my api routes with /api
. This makes it easier when serving the application in production because you can return the app on all routes that don't begin with /api
and it makes the proxy config just as simple because you only need to setup one rule as opposed to potentially multiple using your current stategy.
这篇关于Angular4-5中代理服务器的实现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!