# json-server-demo **Repository Path**: it155/json-server-demo ## Basic Information - **Project Name**: json-server-demo - **Description**: json-server-demo - **Primary Language**: JavaScript - **License**: MIT - **Default Branch**: master - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 0 - **Forks**: 0 - **Created**: 2024-07-11 - **Last Updated**: 2024-12-12 ## Categories & Tags **Categories**: Uncategorized **Tags**: None ## README ### json-server详解 #### 1、简介 - Json-server 是一个零代码快速搭建本地 RESTful API 的工具。它使用 JSON 文件作为数据源,并提供了一组简单的路由和端点,可以模拟后端服务器的行为。 - github地址:https://github.com/typicode/json-server - npm地址:https://www.npmjs.com/package/json-server #### 2、安装 - json-server是基于npm安装的,安装了node就自动安装了npm,所以安装json-server需要先安装node,node相关知识请参考[node入门](https://blog.csdn.net/liyou123456789/article/details/131240626),npm相关知识请参考[npm入门](https://blog.csdn.net/liyou123456789/article/details/131241258)。 - 安装json-server:使用npm或yarn全局安装json-server。 ```bash npm install -g json-server@0.17.4 ``` - 验证安装是否成功:显示版本号就是安装成功了 ```bash json-server -v ``` #### 3、快速使用 (1)创建JSON文件:创建一个JSON文件作为数据源,例如 `db.json`,并在其中定义你想要模拟的数据,例如: ```json { "posts": [ { "id": 1, "title": "json-server", "author": "typicode" } ], "comments": [ { "id": 1, "body": "some comment", "postId": 1 } ], "profile": { "name": "typicode" } } ``` (2)启动json-server:使用以下命令启动json-server,并将JSON文件作为参数传递给服务器。这将在本地计算机的3000端口上启动服务器,并将db.json文件中的数据暴露为RESTful API。 ```bash json-server --watch db.json ``` (3)访问地址:http://localhost:3000,可以分别点击`/posts` `/comment` `/profile` 链接,能看到各自的json数据。 #### 4、参数说明 - 语法:`json-server [options] ` | 参数 | 简写 | 说明 | 默认值 | | --------- | ---- | ---------------------- | ------------------------ | | --config | -c | 指定配置文件 | 默认值:json-server.json | | --port | -p | 指定端口 | 默认值:3000 | | --host | -h | 指定主机名 | 默认值:localhost | | --watch | -w | 监听文件变化 | 默认值:db.json | | --static | -s | 指定静态文件文件夹路径 | | | --help | -h | 显示帮助信息 | | | --version | -v | 显示版本号 | | ##### (1)修改端口 - json-server 默认是 3000 端口,我们也可以自己指定端口,指令如下: ```bash json-server --watch db.json --port 8888 ``` ##### (2)修改IP地址 - json-server 默认IP地址是 localhost,我们也可以自己指定IP地址,指令如下: ```bash json-server --watch db.json --port 8888 --host 192.168.0.100 ``` ##### (3)静态服务器 - 配置静态资源服务器:主要是用来配置图片、音频、视频资源 - `./static`是静态文件路径,里面放一张图片`test.jpg` - 服务启动后,直接在浏览器输入http://localhost:3000/test.jpg就能访问到这张图片 ```bash json-server -s ./static db.json ``` #### 5、增删改查 ##### (1)准备数据 - 我们准本一个测试数据`db.json`,注意数据格式要符合JSON格式,如果数据格式有误,命令窗口会报错,可以根据错误提示进行修整。 - 启动服务:`json-server --watch db.json` ```json { "fruits": [ { "id": 1, "name": "糖心富士苹果", "price": 2.38 }, { "id": 2, "name": "橘子", "price": 3.88 }, { "id": 3, "name": "宁夏西瓜", "price": 1.98 }, { "id": 4, "name": "麒麟西瓜", "price": 3.98 }, { "id": 5, "name": "红蛇果", "price": 2.5 }, { "id": 6, "name": "黑皮西瓜", "price": 0.98 }, { "id": 7, "name": "红心火龙果", "price": 2.69 }, { "id": 8, "name": "国产火龙果", "price": 1.69 }, { "id": 9, "name": "海南荔枝", "price": 9.9 }, { "id": 10, "name": "陕西冬枣", "price": 5.39 }, { "id": 11, "name": "软籽石榴", "price": 2.39 }, { "id": 12, "name": "蜜橘", "price": 1.99 }, { "id": 13, "name": "海南香蕉", "price": 1.45 } ], "users": [ { "name": { "username":"admin", "nickname":"zhangsan" }, "pwd": "123456" } ] } ``` ##### (2)获取全部数据 获取所有文章内容,返回`对象数组` ```url http://localhost:3000/articles ``` ##### (3)过滤 - 根据id获取数据,返回`单个对象` ```url http://localhost:3000/fruits/1 ``` ```json { "id": "1", "name": "糖心富士苹果", "price": 2.38 } ``` - 还可以用url参数写法,返回`对象数组`,也可以指定多个条件,用`&`符号连接,返回`对象数组` ```url http://localhost:3000/fruits?id=1 http://localhost:3000/fruits?name=糖心富士苹果 http://localhost:3000/fruits?name=糖心富士苹果&price=2.38 //指定多个条件,用&符号连接 ``` ```json [ { "id": "1", "name": "糖心富士苹果", "price": 2.38 } ] ``` - 对象取属性值`obj.key`的方式 ```url http://localhost:3000/users?name.nickname=zhangsan ``` ```json [ { "name": { "username": "admin", "nickname": "zhangsan" }, "pwd": "123456", "id": "afe9" } ] ``` - `_start` 来指定开始位置, `_end` 来指定结束位置,或者是用`_limit`来指定从开始位置起往后取几个数据 ```url http://localhost:3000/fruits?_start=0&_end=2 ``` ```json [ { "id": "1", "name": "糖心富士苹果", "price": 2.38 }, { "id": "2", "name": "橘子", "price": 3.88 } ] ``` ```url http://localhost:3000/fruits?_start=2&_limit=4 ``` ```json [ { "id": "3", "name": "宁夏西瓜", "price": 1.98 }, { "id": "4", "name": "麒麟西瓜", "price": 3.98 }, { "id": "5", "name": "红蛇果", "price": 2.5 }, { "id": "6", "name": "黑皮西瓜", "price": 0.98 } ] ``` - 用`_like`来设置模糊匹配某个字段 ``` http://192.168.0.112:3000/fruits?name_like=西瓜 ``` ``` [ { "id": "3", "name": "宁夏西瓜", "price": 1.98 }, { "id": "4", "name": "麒麟西瓜", "price": 3.98 }, { "id": "6", "name": "黑皮西瓜", "price": 0.98 } ] ``` - 用`_ne`来设置不包含某个值 ```url http://192.168.0.112:3000/fruits?name_ne=黑皮西瓜&name_ne=海南香蕉 ``` ```json [ { "id": 1, "name": "糖心富士苹果", "price": 2.38 }, { "id": 2, "name": "橘子", "price": 3.88 }, { "id": 3, "name": "宁夏西瓜", "price": 1.98 }, { "id": 4, "name": "麒麟西瓜", "price": 3.98 }, { "id": 5, "name": "红蛇果", "price": 2.5 }, { "id": 7, "name": "红心火龙果", "price": 2.69 }, { "id": 8, "name": "国产火龙果", "price": 1.69 }, { "id": 9, "name": "海南荔枝", "price": 9.9 }, { "id": 10, "name": "陕西冬枣", "price": 5.39 }, { "id": 11, "name": "软籽石榴", "price": 2.39 }, { "id": 12, "name": "蜜橘", "price": 1.99 } ] ``` ##### (4)分页 - 分页采用 _page 来设置页码, _limit 来控制每页显示条数。如果没有指定 _limit ,默认每页10条。 ```url http://localhost:3000/fruits?_page=2&_limit=5 ``` ```json [ { "id": "1", "name": "糖心富士苹果", "price": 2.38 }, { "id": "2", "name": "橘子", "price": 3.88 }, { "id": "3", "name": "宁夏西瓜", "price": 1.98 }, { "id": "4", "name": "麒麟西瓜", "price": 3.98 }, { "id": "5", "name": "红蛇果", "price": 2.5 } ] ``` ##### (5)排序 - 排序采用`_sort` 指定要排序的字段,`_order` 指定升序还是降序(asc | desc ,默认是asc) ```url http://localhost:3000/fruits?_sort=price&_order=desc ``` ```json [ { "id": "9", "name": "海南荔枝", "price": 9.9 }, { "id": "10", "name": "陕西冬枣", "price": 5.39 }, { "id": "4", "name": "麒麟西瓜", "price": 3.98 }, { "id": "2", "name": "橘子", "price": 3.88 }, { "id": "7", "name": "红心火龙果", "price": 2.69 }, { "id": "5", "name": "红蛇果", "price": 2.5 }, { "id": "11", "name": "软籽石榴", "price": 2.39 }, { "id": "12", "name": "蜜橘", "price": 1.99 }, { "id": "3", "name": "宁夏西瓜", "price": 1.98 }, { "id": "8", "name": "国产火龙果", "price": 1.69 }, { "id": "13", "name": "海南香蕉", "price": 1.45 }, { "id": "6", "name": "黑皮西瓜", "price": 0.98 } ] ``` - 还可以指定多个字段排序,先排前面字段,前面字段相同的再排第二个字段,默认:升序 ```url http://localhost:3000/fruits?_sort=price,id ``` ```json [ { "id": "6", "name": "黑皮西瓜", "price": 0.98 }, { "id": "13", "name": "海南香蕉", "price": 1.45 }, { "id": "8", "name": "国产火龙果", "price": 1.69 }, { "id": "3", "name": "宁夏西瓜", "price": 1.98 }, { "id": "12", "name": "蜜橘", "price": 1.99 }, { "id": "1", "name": "糖心富士苹果", "price": 2.38 }, { "id": "11", "name": "软籽石榴", "price": 2.39 }, { "id": "5", "name": "红蛇果", "price": 2.5 }, { "id": "7", "name": "红心火龙果", "price": 2.69 }, { "id": "2", "name": "橘子", "price": 3.88 }, { "id": "4", "name": "麒麟西瓜", "price": 3.98 }, { "id": "10", "name": "陕西冬枣", "price": 5.39 }, { "id": "9", "name": "海南荔枝", "price": 9.9 } ] ``` ##### (6)全文搜索 ```url http://192.168.0.112:3000/fruits?q=国产火龙果 ``` ```json [ { "id": "8", "name": "国产火龙果", "price": 1.69 } ] ``` ##### (7)查询数据 > 案例:获取db.json中的所有水果信息,以表格的方式展现出来,[jquery.js下载](https://releases.jquery.com/jquery/)。 ```html 使用jquery ajax方法操作数据
``` ##### (8)添加数据 > POST 方法:常用来创建一个新资源。 案例:在页面的输入框中输入新的水果名称和价格,通过POST添加到db.json中。 ```html
水果:
价格:
``` ```js $("#postBtn").click(function () { $.ajax({ type: 'post', url: 'http://localhost:3000/fruits', data: { name: $("#fruitName").val(), price: $("#fruitPrice").val() }, success: function (data) { console.log("post success") }, error: function () { alert("post error") } }) }) ``` ##### (9)更新数据 > PUT 方法:常用来更新已有资源,若资源不存在,它也会进行创建。 > 案例:输入水果对应id,修改其价格。 ```html
水果id:
价格:
``` ```js $("#putBtn").click(function () { $.ajax({ type: 'put', url: 'http://localhost:3000/fruits/' + $("#putId").val(), data: { price: $("#putPrice").val() }, success: function (data) { console.log("put success") }, error: function () { alert("put error") } }) }) ``` > 这是因为,`PUT方法会更新整个资源对象,前端没有给出的字段,会自动清空`。所以,要么我们在ajax的data中给出完整的对象信息,要么采用PATCH方法。`PATCH`是一个新方法,可以当作是PUT方法的补充,主要用来做`局部更新`。 > 案例:同PUT方法。 ```js $("#putBtn").click(function () { $.ajax({ type: 'patch', url: 'http://localhost:3000/fruits/' + $("#putId").val(), data: { price: $("#putPrice").val() }, success: function (data) { console.log("put success") }, error: function () { alert("put error") } }) }) ``` > 但有时候,我们更希望能通过输入水果名称,来动态更新水果价格。但 ‘http://localhost:3000/fruits/橘子’ 这种 url 是错误的,而像 ‘http://localhost:3000/fruits?name = 橘子’ 这种url,只能供 GET 方法来获取数据。既然如此,我们就多绕个弯,通过GET方法来获知id,然后再通过id去PATCH数据。 > 实现方法如下: ```html
水果:
价格:
``` ```js $("#editBtn").click(function () { getFun($("#editName").val(), patchFun) }) function getFun(name, f) { $.ajax({ type: 'get', url: 'http://localhost:3000/fruits' + '?name=' + name, success: function (data) { // data 对象数组 console.log(data[0]); if (typeof f == "function") f.call(this, data[0].id) }, error: function () { alert("error") } }) } function patchFun(id) { $.ajax({ type: 'patch', url: 'http://localhost:3000/fruits/' + id, data: { price: $("#editPrice").val() }, success: function (data) { console.log("success", data) }, error: function () { alert("error") } }) } ``` ##### (10)删除数据 > DELETE 方法:常用来删除已有资源。 案例:根据id删除水果数据 ```html

删除水果

水果id:
``` ```js $("#delOne").click(function () { $.ajax({ type: 'delete', url: 'http://localhost:3000/fruits/' + $("#delId").val(), success: function (data) { console.log("del success") }, error: function () { alert("del error") } }) }) ``` >若想要删除全部,没办法使用’http://localhost:3000/fruits’ 这种请求url。因为必须指定删除的对象id,所以只能通过循环删除,这就需要实现通过GET方法来获取当前最大id(注意是最大id,而不是数据个数)来作为循环的边界。 ```json $("#delAll").click(function () { // 此处就没有动态去获取db.json中fruits的最大id,直接带入10 for (var i = 0; i <= 10; i++) { delFun(i) } }) function delFun(id) { $.ajax({ type: 'delete', url: 'http://localhost:3000/fruits/' + id, data: '', success: function (data) { console.log("del success", data) }, error: function () { console.log("del error") } }) } ``` #### 6、配置静态资源服务器 >主要是用来配置图片、音频、视频资源; >通过命令行配置路由、数据文件、监控等会让命令变的很长,而且容易敲错; >json-server允许我们把所有的配置放到一个配置文件中,这个配置文件一般命名为`json_sever_config.json`。 ##### json_sever_config.json ``` { "static": "./public", "read-only": false, "no-cors": false, "no-gzip": false } ``` 我们可以把我们的图片资源都放在public目录中。public目录不仅可以放图片,也可以放音频和视频,所以大家放资源的时候,在public下面创建images用来放置图片,创建audio/video分别放置音频和视频。既然我们已经在json_server_config.json里面指明了静态文件的目录,那么我们访问的时候,就可以忽略public ```url http://localhost:3000/图片名称 ``` ##### package.json ``` { "scripts": { "mock": "json-server --config json_sever_config.json --watch db.json --port 3000 --host localhost" } } ``` 配置package.json后,我们就可以用以下命令来启动项目 ```bash npm run mock ```