美文网首页
json-server 搭建自己的本地数据

json-server 搭建自己的本地数据

作者: 琳媚儿 | 来源:发表于2020-04-11 15:35 被阅读0次

1,使用npm 全集安装json-server

npm install -g json-server

淘宝镜像

npm install -g json-server --registry=https://registry.npm.taobao.org

可以通过查看版本号,来测试是否安装成功:

json-server -v

2,创建json数据——db.json
创建了一个myserver文件夹,进入到该文件夹里面,执行代码:

json-server --watch db.json
启动本地的IP地址
查询本地的IP
npx json-server --host 0.0.0.0 db.json

ipconfig


image

json-server 默认是 3000 端口,我们也可以自己指定端口,指令如下:

json-server --watch db.json --port 3004

觉得启动服务的这段代码有点长,还可以考虑db.json同级文件夹(也就是myserver文件夹)新建一个package.json,把配置信息写在里头:

{
    "scripts": {
        "mock": "json-server db.json --port 3004"
    }
}

之后启动服务,只需要执行如下指令就可以了

npm run mock

3操作数据
(1)GET

http://localhost:3004/fruits  获得所有数据

过滤获取 Filter: 获取第一个元素

http://localhost:3004/fruits/1

{
  "id": 1,
  "name": "apple",
  "price": "33"
}

当然,指定id为1的获取指令还可以用如下指令,但要注意,此时返回的数据是一个数组。

http://localhost:3004/fruits?id=1

以此类推,我们也可以通过水果名称,或者是价格来获取数据:

http://localhost:3004/fruits?name=orange

分页采用 _page 来设置页码, _limit 来控制每页显示条数。如果没有指定 _limit ,默认每页显示10条。

http://localhost:3004/fruits?_page=2&_limit=2


[
  {
    "id": 3,
    "name": "apple3",
    "price": "3"
  },
  {
    "id": 4,
    "name": "apple4",
    "price": "4"
  }
]

排序 Sort
排序采用 _sort 来指定要排序的字段, _order 来指定排序是正排序还是逆排序(asc | desc ,默认是asc)。

http://localhost:3004/fruits?_sort=id&_order=desc

取局部数据 Slice
slice的方式,和 Array.slice() 方法类似。采用 _start 来指定开始位置, _end 来指定结束位置、或者是用_limit来指定从开始位置起往后取几个数据。

http://localhost:3004/fruits?_start=2&_end=4

取符合某个范围 Operators
(1)采用 _gte _lte 来设置一个取值范围(range):

http://localhost:3004/fruits?id_gte=4&id_lte=6

(2)采用_ne来设置不包含某个值:

http://localhost:3004/fruits?id_ne=1

相关文章

网友评论

      本文标题:json-server 搭建自己的本地数据

      本文链接:https://www.haomeiwen.com/subject/fkoymhtx.html