json-server使用及路由配置

1.先安装node.js,node.js中包含了json-server模块

2.在angular-hello/src/app/data-base.json文件中,编辑json格式的服务数据,

{  

  "GetUsers":[
    {
      "id":1,
      "Name":"zhaoling"
    },
    {
      "id":2,
      "Name":"lst"
    }
  ]

}

3.启动服务

cd angular-hello

json-server ./src/app/data-base.json

4.访问接口

http://localhost:3000/GetUsers 返回所有数据(数组)

http://localhost:3000/GetUsers/1 返回id=1的数据,采用这种路径风格id必须为小写 (数组)

http://localhost:3000/GetUsers/?Name=lst 返回Name=lst的用户数据(数组)

5.自定义路由

这是我们在开发过程中在本地虚拟的wepapi服务,假设我们最终部署时要调用第三方真实的api接口是这种形式

http://www.xxxx.com/WepApi/Users/Gets?Name=lst ,

为了部署时方便,显然不能在开发时用本地虚拟服务路径格式,而在部署时一一替换,最好的做法是只改变路径前部分的IP或域名,而后部分的格式不需改变就能轻松切换。

(1)angular-hello/src/app/data-routes.json文件中编写路由映射

{
  "/WepApi/Users/Gets?Name=:Name":"/GetUsers?Name=:Name"
}
WepApi/Users/Gets?Name=:Name 是真实部署时要访问的api路径
/GetUsers?Name=:Name是我们开发时虚拟的api路径
 
程序中就可以这样写了
private apiUrl:string = 'http://localhost:3000/WebApi/';
getUsers(name:string){
  return this.http.request({
    method:'get',
    url: this.apiUrl+'Users/Gets',
    data:{
      Name:name
    }
  });
}
 
在部署时我们只需把http://localhost:3000/WebApi/ 替换成  http://真实的地址/WebApi/  就可以了
 
(2)启动服务
cd angular-hello
json-server ./src/app/data-base.json --routes ./src/app/data-routes.json
 
可以用 http://localhost:3000/WepApi/Users/Gets?Name=:Name":"/GetUsers?Name=lst
代替  http://localhost:3000/GetUsers/?Name=lst 了。
 
原文地址:https://www.cnblogs.com/lvshoutao/p/8549004.html