json-server的简单使用

json-server 是一款小巧的接口模拟工具,可以很快搭建一套 Restful 风格的 API,尤其适合前端接口测试使用。只需指定一个 json文件作为 api 的数据源即可,使用起来非常方便。

安装json-server

npm仓库地址:json-server - npm (npmjs.com)

环境依赖
  • 安装 Node.js 环境即可

操作步骤

全局安装 JSON 服务器

npm install -g json-server

创建一个db.json包含一些数据的文件:

{
  "posts": [
    { "id": "1", "title": "a title", "views": 100 },
    { "id": "2", "title": "another title", "views": 200 }
  ],
  "comments": [
    { "id": "1", "text": "a comment about post 1", "postId": "1" },
    { "id": "2", "text": "another comment about post 1", "postId": "1" }
  ],
  "profile": {
    "name": "typicode"
  }
}

启动 json-server 接口服务器 :端口号可以改

#快速配置
json-server .\db.json

#自定义端口配置
json-server .\db.json --watch --port 3000

 启动成功结果

打开其中一个路径可以成功展示数据

json-server基础操作—增删改查 (使用axios)

查询(GET),或者直接在浏览器访问
axios.get("http://localhost:3000/posts/1").then(res => {
            console.log(res.data)
        })
新增(POST)
axios.post("http://localhost:3000/posts",{
    title: "Real",
    views: 111
})
修改(PUT和PATCH)

PUT和PATCH的区别在于,PUT是覆盖(会把没修改的删除),PATCH是更新(不会把没修改的删除)

axios.put("http://localhost:3000/posts/1",{
    title: "xiaoming",
})

axios.patch("http://localhost:3000/posts/1",{
    title: "xiaoming",
})
删除(DELETE):删除id为1的
axios.delete("http://localhost:3000/posts/1")

数据中的comments中的postId关联posts中的id,一旦posts中id为1的被删除了,连带着postId为1的全部也会被删除。

由此引出两种关系拼接

  • 包含子资源 _embed
  • 包含父资源 _expand
包含子资源 _embed
//将posts里id为1的数据找出来并和子资源comments拼接
axios.get("http://localhost:3000/posts/1?_embed=comments").then(res => {
            console.log(res.data)
        })

 包含父资源 _expand

axios.get("http://localhost:3000/comments?_expand=posts").then(res => {
            console.log(res.data)
        })

结语:写这个主要是记录一下,只会一点简单的,下面是一个写得很好的文章

json-server从入门开始 - 掘金 (juejin.cn)

  • 9
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值