json-server 快速上手

361 阅读2分钟

json-server 快速上手

1、全局安装 json-server

npm install -g json-server

2、运行 json-server,

json-server --watch db.json
​
# 运行完上面这条命令之后,会在当前文件夹下自动创建一个 db.json 文件。

接口说明

db.json文件的内容

image-20220927214420590.png

开启的接口

image-20220927214453377.png

也就是说,每一个接口对应着db.json文件中的一个子对象。

json-server 的相关启动参数

语法:json-server [options] <source>

选项列表:

参数简写默认值说明
--config-c指定配置文件[默认值: "json-server.json"]
--port-p设置端口 [默认值: 3000]Number
--host-H设置域 [默认值: "0.0.0.0"]String
--watch-wWatch file(s)是否监听
--routes-r指定自定义路由
--middlewares-m指定中间件 files[数组]
--static-sSet static files directory静态目录,类比:express的静态目录
--readonly--roAllow only GET requests [布尔]
--nocors--ncDisable Cross-Origin Resource Sharing [布尔]
--nogzip, --ng Disable GZIP Content-Encoding [布尔]
--snapshots-SSet snapshots directory [默认值: "."]
--delay-dAdd delay to responses (ms)
--id-iSet database id property (e.g. _id) [默认值: "id"]
--foreignKeySuffix--fks Set foreign key suffix (e.g. _id as in post_id)[默认值: "Id"]
--help-h显示帮助信息[布尔]
--version-v显示版本号[布尔]

其他

接口的规范

一般来说响应接口会包含以下三个部分

  • code
  • message
  • data

修改接口的端口号

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

如果你觉得输入命令来启动这个服务有点麻烦,可以在db.json同级的目录下,新建一个package.json文件。里面写入以下内容。

{
  "scripts": {
    "api":"json-server --watch db.json"
  }
}

请求

我们自己折腾一下 db.json。加入以下内容

"fruits": [
        {
            "id": 1,
            "name": "苹果",
            "price": 1.28
        },
        {
            "id": 2,
            "name": "橘子",
            "price": 3.88
        },
        {
            "id": 3,
            "name": "西瓜",
            "price": 1.98
        }
    ],

get请求

获取所有数据 - http://localhost:3000/fruits

获取id为1的数据(对象)- http://localhost:3004/fruits/1

获取id为1的数据(数组)- http://localhost:3000/fruits?id=1

获取name为苹果的数组 - http://localhost:3000/fruits?name=%E8%8B%B9%E6%9E%9C

多个条件 - http://localhost:3004/fruits?name=橘子&price=3.88

分页请求

http://localhost:3000/fruits?_page=1&_limit=5

_page表示当前请求所在的页面

_limit表示限定每页有多少个元素

排序请求

http://localhost:3000/fruits?_sort=id&_order=asc

_sort表示以什么进行排序

_order表示倒序还是正序(asc、desc)

取局部数据

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

全文搜索

http://localhost:3004/fruits?q=3

?q=关键词


post请求

增加数据

body参数

{
    "name":"红宝石葡萄",
    "price":9.22
}

patch局部更新数据

http://localhost:3000/fruits/1

参数形式:x-form-www-urlencoded

put全局更新数据

形式如上

delete删除数据

http://localhost:3000/fruits/14