【json-server】json-server安装与使用:

这篇具有很好参考价值的文章主要介绍了【json-server】json-server安装与使用:。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。


一、下载安装:

【json-server网址】https://www.npmjs.com/package/json-server

#使用npm全局安装json-server:
npm install -g json-server

#可以通过查看版本号,来测试是否安装成功:
json-server -v
二、启动db.json数据及相关参数:
json-server --watch .\db.json --port 5000

json安装,软件与插件,json,arcgis

参数 简写 默认值 说明
–config -c 指定配置文件 [默认值: “json-server.json”]
–port -p 设置端口 [默认值: 3000]
–host -H 设置域 [默认值: “0.0.0.0”]
–watch -w Watch file(s) 是否监听
–routes -r 指定自定义路由
–middlewares -m 指定中间件 files [数组]
–static -s Set static files directory 静态目录,类比:express的静态目录
–readonly –ro Allow only GET requests [布尔]
–nocors –nc Disable Cross-Origin Resource Sharing [布尔]
–no-gzip –ng Disable GZIP Content-Encoding [布尔]
–snapshots -S Set snapshots directory [默认值: “.”]
–delay -d Add delay to responses(ms)
–id -i Set 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 显示版本号 [布尔]

编辑过db.json(db.json数据有变动),都要关闭服务重新启动。(注意:不要用 CTRL + C 来停止服务,因为这种方式会导致 node.js 依旧霸占着3004端口,导致下一次启动失败。简单粗暴关闭窗口即可! —— 个人window系统,其他系统可能没有这样的烦恼。)

三、创建json数据——db.json:

既然是造数据,就需要创建一个json数据。在任意一个文件夹下(此处假设我创建了一个myserver文件夹),进入到该文件夹里面,执行代码:

json-server --watch db.json

原本空空如也的文件夹里,就会多出一个db.json文件。同时,根据执行代码结果的提示,我们可以访问 http://localhost:3000 (启动json-server后,点击才有效),看到如下页面:可以分别点击/posts /comment /profile /db链接,看看页面跳转后,观察地址栏变化和页面内容,你看到了什么?没错,就是各自的json数据。

#db.json里面自带的数据:
{
  "posts": [
    {
      "id": 1,
      "title": "json-server",
      "author": "typicode"
    }
  ],
  "comments": [
    {
      "id": 1,
      "body": "some comment",
      "postId": 1
    }
  ],
  "profile": {
    "name": "typicode"
  }
}

再比对myserver/db.json文件的数据,就可以发现: /db就是整个的db.json数据包,而/posts /comment /profile 分别是db.json里面的子对象。所以说,json-server把db.json 根节点的每一个key,当作了一个router。我们可以根据这个规则来编写测试数据。

四、修改端口号:

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
五、操作数据GET:
{
    "fruits": [
        {
            "id": 1,
            "name": "苹果",
            "price": 1.28
        },
        {
            "id": 2,
            "name": "橘子",
            "price": 3.88
        },
        {
            "id": 3,
            "name": "西瓜",
            "price": 1.98
        }
    ],
    "users": [
        {
            "name": {
                "username":"admin",
                "nickname":"zhangsan"
            },
            "pwd": "123456"
        }
    ]
}
【1】常规获取:

http://localhost:3004/fruits =》可以得到所有水果数据(对象数组

[
    {
        "id": 1,
        "name": "苹果",
        "price": 1.28
    },
    {
        "id": 2,
        "name": "橘子",
        "price": 3.88
    },
    {
        "id": 3,
        "name": "西瓜",
        "price": 1.98
    }
]
【2】过滤获取 Filter:

返回的数据是一个对象
【1】http://localhost:3004/fruits/1

{
    "id": 1,
    "name": "苹果",
    "price": 1.28
}

返回的数据是一个数组
【2】http://localhost:3004/fruits?id=1
【3】http://localhost:3004/fruits?name=苹果
【4】 http://localhost:3004/fruits?name=苹果&price=1.28 //指定多个条件,用&符号连接

[
    {
        "id": 1,
        "name": "苹果",
        "price": 1.28
    }
]

【5】对象取属性值obj.key的方式: http://localhost:3004/users?name.nickname=zhangsan

[
  {
    "name": {
      "username": "admin",
      "nickname": "zhangsan"
    },
    "pwd": "123456"
  }
]
【3】分页 Paginate:
{
    "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"
        }
    ]
}

编辑过db.json(db.json数据有变动),都要关闭服务重新启动。(注意:不要用 CTRL + C 来停止服务,因为这种方式会导致 node.js 依旧霸占着3004端口,导致下一次启动失败。简单粗暴关闭窗口即可! —— 个人window系统,其他系统可能没有这样的烦恼。)

分页采用 _page 来设置页码, _limit 来控制每页显示条数。如果没有指定 _limit ,默认每页显示10条。
http://localhost:3004/fruits?_page=2&_limit=5
json安装,软件与插件,json,arcgis

【4】排序 Sort:

排序采用 _sort 来指定要排序的字段, _order 来指定排序是正排序还是逆排序(asc | desc ,默认是asc
http://localhost:3004/fruits?_sort=price&_order=desc
json安装,软件与插件,json,arcgis
也可以指定多个字段排序,一般是按照price进行排序后,相同price的再根据id排序:
http://localhost:3004/fruits?_sort=price,id&_order=desc,asc

【5】取局部数据 Slice

slice的方式,和 Array.slice() 方法类似。采用 _start 来指定开始位置, _end 来指定结束位置、或者是用_limit来指定从开始位置起往后取几个数据。
http://localhost:3004/fruits?_start=0&_end=2
json安装,软件与插件,json,arcgis
http://localhost:3004/fruits?_start=2&_limit=4
json安装,软件与插件,json,arcgis

【6】取符合某个范围 Operators

【1】采用 _gte _lte 来设置一个取值范围(range):

http://localhost:3004/fruits?id_gte=4&id_lte=6
json安装,软件与插件,json,arcgis

【2】采用_ne来设置不包含某个值:

http://localhost:3004/fruits?id_ne=1&id_ne=10
json安装,软件与插件,json,arcgis

【3】采用_like来设置匹配某个字符串(或正则表达式):

http://localhost:3004/fruits?name_like=果
json安装,软件与插件,json,arcgis

【7】全文搜索 Full-text search: 采用 q 来设置搜索内容

http://localhost:3004/fruits?q=3
json安装,软件与插件,json,arcgis

【8】案例

获取db.json中的所有水果信息,以表格的方式展现出来
json安装,软件与插件,json,arcgis

<!DOCTYPE html>
<html>

<head>
  <title>使用jquery ajax方法操作数据</title>
  <script type="text/javascript" src="./jquery.js"></script>
  <style>
    table,
    td,
    th {
      border: 1px solid black;
      border-collapse: collapse;
    }

    table {
      width: 500px;
      text-align: center;
    }

    tr {
      height: 35px;
    }
  </style>
</head>

<body>
  <button id="getBtn">获取所有水果数据</button>
  <div id="showData"></div>

  <script type="text/javascript">
    $("#getBtn").click(function () {
      $.ajax({
        type: 'get',
        url: 'http://localhost:3004/fruits',
        success: function (data) {
          // data 对象数组
          var h = ""
          h += "<table border='1'>"
          h += "<thead><th>ID</th><th>name</th><th>price</th></thead>"
          h += "<tbody>"
          for (var i = 0; i < data.length; i++) {
            var o = data[i]
            h += "<tr>"
            h += "<td>" + o.id + "</td><td>" + o.name + "</td><td>" + o.price + "</td>"
            h += "</tr>"
          }
          h += "<tbody>"
          h += "</table>"
          $("#showData").empty().append(h)
        },
        error: function () {
          alert("get : error")
        }
      })
    })
  </script>
</body>

</html>

json安装,软件与插件,json,arcgis

六、添加数据:POST 方法,常用来创建一个新资源。

案例:在页面的输入框中输入新的水果名称和价格,通过post添加到db.json中。

水果:<input id="fruitName" type="text" name="fruitName"><br>
价格:<input id="fruitPrice" type="text" name="fruitPrice"><br>
<button id="postBtn">添加水果</button>
$("#postBtn").click(function () {
    $.ajax({
        type: 'post',
        url: 'http://localhost:3004/fruits',
        data: {
            name: $("#fruitName").val(),
            price: $("#fruitPrice").val()
        },
        success: function (data) {
            console.log("post success")
        },
        error: function () {
            alert("post error")
        }
    })
})

json安装,软件与插件,json,arcgis

七、更新数据:PUT 方法,常用来更新已有资源,若资源不存在,它也会进行创建;PATCH:局部更新

案例:输入水果对应id,修改其价格。

<p>更新水果价格</p>
水果id:<input id="putId" type="text" name="fruitId"><br>
价格:<input id="putPrice" type="text" name="fruitPrice"><br>
<button id="putBtn">put更新</button>
$("#putBtn").click(function () {
    $.ajax({
        type: 'put',
        url: 'http://localhost:3004/fruits/' + $("#putId").val(),
        data: {
            price: $("#putPrice").val()
        },
        success: function (data) {
            console.log("put success")
        },
        error: function () {
            alert("put error")
        }
    })
})

json安装,软件与插件,json,arcgis

这是因为,PUT方法会更新整个资源对象,前端没有给出的字段,会自动清空。所以,要么我们在ajax的data中给出完整的对象信息,要么采用PATCH方法。PATCH是一个新方法,可以当作是PUT方法的补充,主要用来做局部更新
案例:同PUT方法。

$("#putBtn").click(function () {
    $.ajax({
        type: 'patch',
        url: 'http://localhost:3004/fruits/' + $("#putId").val(),
        data: {
            price: $("#putPrice").val()
        },
        success: function (data) {
            console.log("put success")
        },
        error: function () {
            alert("put error")
        }
    })
})

json安装,软件与插件,json,arcgis

但有时候,我们更希望能通过输入水果名称,来动态更新水果价格。但 ‘http://localhost:3004/fruits/橘子’ 这种 url 是错误的,而像 ‘http://localhost:3004/fruits?name = 橘子’ 这种url,只能供 GET 方法来获取数据。既然如此,我们就多绕个弯,通过GET方法来获知id,然后再通过id去PATCH数据。
实现方法如下:

<p>通过水果名更新水果价格</p>
水果:<input id="editName" type="text" name="fruitName"><br>
价格:<input id="editPrice" type="text" name="fruitPrice"><br>
<button id="editBtn">edit</button>
$("#editBtn").click(function () {
    getFun($("#editName").val(), patchFun)
})
 
function getFun(name, f) {
    $.ajax({
        type: 'get',
        url: 'http://localhost:3004/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:3004/fruits/' + id,
        data: {
            price: $("#editPrice").val()
        },
        success: function (data) {
            console.log("success", data)
        },
        error: function () {
            alert("error")
        }
    })
}
八、删除数据: DELETE 方法,常用来删除已有资源

案例:根据id删除水果数据

<p>删除水果</p>
水果id:<input id="delId" type="text" name="delName"><br>
<button id="delOne">根据id删除</button>
<button id="delAll">删除所有</button>
$("#delOne").click(function () {
    $.ajax({
        type: 'delete',
        url: 'http://localhost:3004/fruits/' + $("#delId").val(),
        success: function (data) {
            console.log("del success")
        },
        error: function () {
            alert("del error")
        }
    })
})

若想用删除全部,没办法使用’http://localhost:3004/fruits’ 这种请求url。因为必须指定删除的对象id。所以只能通过循环删除。这就需要实现通过GET方法来获取当前最大id(注意是最大id,而不是数据个数)来作为循环的边界。

$("#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:3004/fruits/' + id,
        data: '',
        success: function (data) {
            console.log("del success", data)
        },
        error: function () {
            console.log("del error")
        }
    })
}
九、关联关系=》向下查找_embed

json安装,软件与插件,json,arcgis

http://localhost:8000/posts?_embed=comments

json安装,软件与插件,json,arcgis

十、关联关系=》向上查找_expand

http://localhost:8000/comments?_expand=post

json安装,软件与插件,json,arcgis

十一、配置静态资源服务器:主要是用来配置图片、音频、视频资源

通过命令行配置路由、数据文件、监控等会让命令变的很长,而且容易敲错;
json-server允许我们把所有的配置放到一个配置文件中,这个配置文件一般命名为json_sever_config.json;

【1】json_sever_config.json
{
  "port": 3004,            
  "watch": true,           
  "static": "./public",
  "read-only": false, 
  "no-cors": false, 
  "no-gzip": false
}
【2】package.json
{
    "scripts": {
        "mock": "json-server --c json_sever_config.json db.json"
    }
}

我们可以把我们的图片资源都放在public目录中,但是public目录不仅可以放图片,也可以放音频和视频,所有大家放资源的时候,在public下面创建images用来放置图片,创建audio/video分别放置音频和视频;
既然我们已经在json_server_config.json里面指明了静态文件的目录,那么我们访问的时候,就可以忽略public;
json安装,软件与插件,json,arcgis
图片:http://localhost:3004/图片名称
json安装,软件与插件,json,arcgis文章来源地址https://www.toymoban.com/news/detail-543865.html

到了这里,关于【json-server】json-server安装与使用:的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • json-server 详解

    这几天在写react的前端项目,想着后端接口没有,在网上也找不到比较合适的接口,所以在github和npm上翻了许久关于前端简单生成后端接口的工具,终于被找到了这个神仙工具 json-server json-server可以直接把一个json文件托管成一个具备全RESTful风格的API,并支持跨域、jsonp、路由订制、

    2024年02月08日
    浏览(31)
  • 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安装的

    2024年02月15日
    浏览(21)
  • json-server操作restful

    1.安装Node.js 默认已经内置npm,下载对应软件包直接安装即可。nodejs的官网 命令 描述 指令 解释 npm -v 查看版本 npm install 模块名 安装模块 npm list 查看所有全局安装的模块 npm list -g 查看某个模块的版本号 npm install --save 模块名 在package.json文件中写入依赖(npm5版本之前需要指定

    2024年02月09日
    浏览(33)
  • json-server 模拟接口数据

    json-server - npm [!IMPORTANT] Viewing alpha v1 documentation – usable but expect breaking changes. For stable version, see [here](https://github.com/typicode/json-server/tree/v0). Latest version: 1.0.0-alpha.21, last published: 6 days ago. Start using json-server in your project by running `npm i json-server`. There are 347 other projects in the npm regis

    2024年01月23日
    浏览(28)
  • 【json-server】centos线上环境搭建全攻略

    描述 开发中经常需要搭建服务器做交互,其中 RESTfull 风格的接口尤为受人青睐,今天我们就要使用 json-server 来搭建一个服务,满足日常工作需要。 环境 版本号 描述 文章日期 2023-06-25 腾讯云 CentOS 7.5 64位 nvm 0.39.3 node -v v16.16.0 npm -v (8.11.0) json-server 0.17.3 安装json-server有很多

    2024年02月11日
    浏览(26)
  • 『前端必备』本地数据接口—json-server 详细介绍(入门篇)

    目录 前言  一、Node环境搭建 1-1 简介 1-2 Node.js环境搭建 1-2-1 下载 1-2-2 安装 1-2-3 验证 1-3 npm简介 二、json-server环境搭建 2-1 简介 2-2 安装 2-3 创建数据库 2-4 启动 ​编辑 2-5 查看 三、操作数据 3-1 查(get) 3-2 增(post) 3-3 删(delete) 3-4 改(put 和 patch) Ajax 是前端必学的一个知

    2024年02月05日
    浏览(32)
  • json-server Node.js 服务,前端模拟后端提供json接口服务

    json-server Node.js 服务,前端模拟后端提供json接口服务 背景:    前后端分离的项目,如果前端写页面的话,必须的后端提供接口文件,作为前端等待时间太久,不便于开发进行,如果前端写的过程中自己搭建一个简要的后端的json服务接口,就是可以快速进行开发事项的进行,

    2024年02月16日
    浏览(30)
  • Mac如何安装brew及使用brew安装软件/插件?

    刚入手一台Mac笔记本,没有啥配置,需要使用脚本安装一些软件或者插件需要使用brew,好记性不如烂笔头,顺手记录下安装过程 1、brew 镜像安装脚本 该安装脚本用了中科大镜像加速访问,仅修改仓库地址部分,不会产生安全隐患。 关于中科大所提供的 Homebrew 镜像服务 htt

    2024年02月14日
    浏览(29)
  • ArcGIS 10.7软件安装包下载及安装教程!

    【软件名称】:ArcGIS 10.7 【安装环境】:Windows 【下载链接 】: 链接:https://pan.baidu.com/s/1IwsPubYWGHd9ztmn45QLJA 提取码:1oeq   复制这段内容后打开百度网盘手机App,操作更方便哦 软件简介 ArcGIS Desktop 软件是一款GSI专业的电子地图信息编辑和开发软件,它主要应用于GIS访问,提

    2024年02月07日
    浏览(39)
  • ArcGIS 10.8软件安装包下载及安装教程

    【软件名称】:ArcGIS 10.6 【安装环境】:Windows 【下载链接 】: 链接:https://pan.baidu.com/s/1wKpTeiFdhMBmbRWrJRCsoA 提取码:0987 复制这段内容后打开百度网盘手机App,操作更方便哦 软件简介 ArcGIS Desktop 软件是一款GSI专业的电子地图信息编辑和开发软件,它主要应用于GIS访问,提供

    2024年02月09日
    浏览(41)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包