美文网首页
JSON Server接口服务桩

JSON Server接口服务桩

作者: halfempty | 来源:发表于2019-05-14 15:55 被阅读0次

    1 概述

    前后端分离, 细化工作的同时, 却也增加了前后端协同的成本

    如果定义好接口, 通过mock技术可以解除前后端耦合, 方便各自独立测试

    JSON-Server语法简单, 上手容易, 可以快速提供接口服务

    Get a full fake REST API with zero coding in less than 30 seconds (seriously)

    2 入门

    2.1 上手

    使用npm安装npm install -g json-server

    创建数据文件db.json

    {
      "fruits": [
        {
          "id": 1,
          "name": "banana",
          "price": 3.96,
          "from": "Hainan"
        },
        {
          "id": 2,
          "name": "pineapple",
          "price": 7.98,
          "from": "Hainan"
        },
        {
          "id": 3,
          "name": "mango",
          "price": 5.00,
          "from": "Vietnam"
        }
      ]
    }
    

    启动服务json-server db.json, 服务默认端口3000

    REST Api使用:

    • 查询全部fruits => http://localhost:3000/fruits

    • 查询ID=2的数据 => http://localhost:3000/fruits/2

    • 新增一条记录 => 使用postman发送post请求, id属性勿须作为参数传递


      1557817266233.png
    • 修改一条记录 => 使用postman发送put请求http://localhost:3000/fruits/4

    • 删除一条记录 => 发送delete请求http://localhost:3000/fruits/4

    2.2 过滤

    • 按属性名匹配 => http://localhost:3000/fruits?name=banana
    • 多条记录 => http://localhost:3000/fruits?id=1&id=2
    • 价格范围 => http://localhost:3000/fruits?price_gte=5
    • 不等于 => http://localhost:3000/fruits?id_ne=2
    • 模糊匹配 => http://localhost:3000/fruits?name_like=an

    2.4 排序

    • 按价格倒序排序 => http://localhost:3000/fruits?_sort=price&_order=desc

    3 进阶

    3.1 生成测试数据

    创建data.js文件

    module.exports = () => {
        const data = { fruits: [] }
        // Create 1000 users
        for (let i = 0; i < 10; i++) {
          data.fruits.push({ id: i, name: `user_${i}`, price: 10.0 + i })
        }
        return data
      }
    

    执行json-server data.js启动服务, 发现已生成10条记录

    3.2 自定义路由

    实际接口路径与json-server很大可能是不同的, 创建路由映射使二者关联

    新增routes.json文件

    {
        "/api/*": "/$1",
        "/fruits?id=:id": "/fruits/:id"
    }
    

    执行json-server db.json --routes routes.json启动服务

    3.3 中间件

    中间件用来过滤请求, 比如权限校验

    新增middle.js文件

    module.exports = (req, res, next) => {
        let token = req.query.token
        if(token != undefined && token.length == 10) {
            next()
        } else {
            res.sendStatus(401)
        }
    }
    

    执行json-server db.json --routes routes.json --middlewares middle.js 启动服务

    相关文章

      网友评论

          本文标题:JSON Server接口服务桩

          本文链接:https://www.haomeiwen.com/subject/tbijaqtx.html