json-server的快速上手使用

json-server

在本地模拟后端接口,这种做法称之为构建前端mock

通过 json-server 就可以在本地根据 json 文件快速创建一个模拟的功能齐全的 api 接口

全局安装 json- serve 模块

npm install -g json-server
或者
yarn global add json-server

准备一个 json 文件

data.json

{
  "list": [
    {
      "name": "张三",
      "age": "20",
      "id": 1
    },
    {
      "name": "李四",
      "age": "5",
      "id": 2
    },
    {
      "name": "王五",
      "age": "30",
      "id": 3
    },
    {
      "name": "赵六",
      "age": "18",
      "id": 4
    }
  ]
}

启动 json-server

-w 表示时刻监听 json 文件的数据,实现双向的动态更新

-p 可以指定接口开启使用的端口

json-server data.json -w -p 4000 

GET 请求数据列表

查询 list 表所有数据

http://localhost:4000/list

查询 list 表指定ID为的2数据

http://localhost:4000/list/2

查询 list 表中 name 为王五 且 age 为 30 的项

http://localhost:4000/list?name=王五&age=30

查询的数据分页

http://localhost:4000/list?_page=1&_limit=2

查询的数据排序

asc 升序

desc 降序

http://localhost:4000/list?_sort=age&_order=asc

查询区间数据

***_gte 大于等于

***_lte 小于等于

http://localhost:4000/list?age_gte=20&age_lte=40

查询包含相关文本的数据

http://localhost:4000/list?q=张三

POST 添加数据

http://localhost:4000/list
 {
     "name": "小明",
     "age": "88",
 }

id 可以不用加,json-server 会自动添加

DELETE 删除数据

删除 id 为 5 的数据

http://localhost:4000/list/5

PATCH 更新数据

修改 id 为 4 的数据的name为小明

http://localhost:4000/list/4
{
     "name": "小明",
 }

以上就是关于 json-server 的简单快速上手使用,如有不对,欢迎指出

更多细节扩展请前往:json-server官网

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值