本文介绍了Angular4-5中Proxy Server的实现的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问题说明:使用 angular-cli 和 Angular-5 开发的客户端/UI,UIhttp://localhost:4200 并且我们在 这意味着所有 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 的结果,即未找到,但是当我在另一个选项卡中点击 url 为 http://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中Proxy Server的实现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-29 18:07