JSON-server 的增删改查

一.json-server工具

作用:

  • json-server可以快速的模拟接口

  • 它是一个基于nodejs的命令行工具,例如:nodemon

安装:

  • npm i json-server -g 全局安装

使用的基本步骤:

  • 新建一个文件夹,名字随意

 

  • 进入文件夹,创建一个json文件,名字随意

 

  • 在json文件中写入内容

{
  "brands": [
    {"id":1,"name":"宝马","ctime":"2020-02-02 10:10:10"},
    {"id":2,"name":"奔驰","ctime":"2021-02-02 10:10:10"},
    {"id":3,"name":"奥迪","ctime":"2022-02-02 10:10:10"}
  ]
}
  • 在当前文件夹,执行启动json-server的服务

 

 

  • 成功的日志

 

 

注意事项:

  • 不能关闭命令行窗口

  • id一定是数字,这样id才能自增

二.增删改查

1.接口规则-RESTful

目标:了解一种接口定义规范resetful

接口规范:如何定义接口地址,请求方式,传参方式,对应不同的请求操作行为。

具体规则:

接口地址请求方式操作行为
/brandsGET查询所有列表
/brands/:idGET查询单个详情 /brands/1
/brandsPOST添加,提交的参数在请求体
/brands/:idDELETE删除 /brands/1
/brands/:idPUT修改 /brands/1 + 请求体{name,cTime} 全部修改
/brands/:idPATCH修改 /brands/1 + 请求体{name} 个别修改

这个表格可以作为接口调用的参考。

2.以axios作为增删改查请求

axios的使用:

  • 查询所有

  • 查询单个

  • 添加操作

  • 删除操作

  • 修改操作

实例代码

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>

<body>

  <script src="./axios.min.js"></script>
  <script>
      // - 查询所有
     axios.get('http://localhost:3000/brands').then(res=>{
         // res 响应报文对象(响应状态行+响应头+响应主体)
        // res.data 就是响应主体(返回的数据)
         console.log(res.data)
       }).catch(err=>{
        // 错误对象
         console.log(err)
       })


      // - 查询单个
     axios.get('http://localhost:3000/brands/2').then(res=>{
         console.log(res.data)
      }).catch(err=>{
         console.log(err)
       })



      // - 添加操作
      // 第二个参数:请求体传参对象
      axios.post('http://localhost:3000/brands',{
        name: '奥拓',
         cTime: new Date()
       }).then(res=>{
         console.log('添加成功')
       })



      // - 删除操作
      axios.delete('http://localhost:3000/brands/4').then(res=>{
        console.log('删除成功')
      })



      // - 修改操作
      // 第二个参数:请求体传参对象
      axios.patch('http://localhost:3000/brands/3',{
         name: '奥拓'
       }).then(res=>{
        console.log('修改成功')
       })

       axios.put('http://localhost:3000/brands/3',{
        name: '奥迪',
         cTime: new Date()
       }).then(res=>{
         console.log('修改成功')
      })

      // - 带查询参数
      // 1. 自己手动在地址栏拼接?后的键值对  ?id=2&name=宝马
      // 2. 可以传对象提交多个筛选条件 
      // 3. get()中第二个参数可以用来提交参数对象  {params:{更多筛选条件}}


      // json-server提供模糊查询  字段_like
      axios.get('http://localhost:3000/brands',{
        params:{
          name_like: '奥'
        }
      }).then(res=>{
        console.log(res.data)
      }).catch(err=>{
        console.log(err)
      })

  </script>
</body>

</html>

  • 12
    点赞
  • 38
    收藏
    觉得还不错? 一键收藏
  • 7
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值