json-server使用

274 阅读2分钟

json-server入门

json-server是能够快速提供给前端接口的服务工具,在没有后端或者后端接口没开发好时使用。

git地址

安装使用

npm i json-server -g

创建一个db.json文件,里面填一些需要用到的假数据

{
  "users": [
    { "id": 1, "name": "zs", "age": "16" }
  ],
  "comments": [
    { "id": 1, "desc": "some comment", "userId": 1 }
  ],
}

启动json-server

json-server --watch db.json

打开localhost:3000/users可以查到json数据中的users属性信息


   [    { "id": 1, "name": "json-server", "age": "16" }  ]
    

配置

1.启动参数

通过json-server --help 查看启动参数

json-server --help

微信图片_20230419140836.png 常用的有--watch 监听文件、--port设置端口 --host设置主机地址

json-server --watch db.json --host 0.0.0.0
2.配置文件

除了启动参数,还可以通过配置文件来配置这些参数 在根目录创建 json-server.json 文件, 然后写下以下代码,然后执行 json-server db.json

{
    "port": 3000,
    "watch": true,
    "static": "./",
    "host": "0.0.0.0"
}

json-server请求

接口地址

属性的开头就表示接口,如图

{
      "users": [
        { "id": 1, "name": "zs", "age": "16", moreInfo: {desc: "xx"} }
      ],
      "comments": [
        { "id": 1, "desc": "some comment", "userId": 1 }
      ],
    }

接口有两个:分别是localhost:3000/userslocalhost:3000/comments

请求方式

1.增删改查

增删改查分别对应post/delete/put/get,如下:


# 获取所有数据, xxx就是属性名(接口地址)

GET /xxx


# 根据id查询信息,获取xxxx下id为1的详细信息

GET /xxx/1


# 添加数据,请求body中必须包含xxx里面的属性数据

POST /xxx

# 修改数据,请求中必须包含修改的数据,通过id来修改

PUT /xxx/1

PATCH  /XXX/1

# 删除数据,通过id来删除

DELETE /xxx/1
2.过滤数据
a.属性联合

可以多个属性一起查询

GET /users?name=李四&age=18
GET /users?moreInfo.desc=xx
b.模糊查询

可以用来模糊搜索,关键字_like

GET /users?name_like=李
c.运算
  • _gte 大于等于
  • _lte 小于等于
  • _ne 不等于
GET /users?id_ne=1
d.排序
  • _sort 设置排序的字段
  • _order 设置排序的方式(升序、降序)
GET /user?_sort=name&_order=asc(升序)
e.全文检索

关键字q

GET /user?q=XXX
f.切片数据
  • _start&_end
GET /users?_start=20&_end=30
GET /users?_start=20&_limit=10