mock 数据模拟

这里介绍一款非常好用的 json-server 数据模拟服务器。用来生成数据接口,以便前端开发者的数据模拟。

  • 全局安装 json-server

    $ npm install -g json-server
    
  • 创建一个 json 文件,假设文件名为 data.json

    {
        "user": [
            {"id": 1, "username": "张三", "password": "abc123"},
            {"id": 2, "username": "李四", "password": "abc456"}
        ],
        "list": [
            {"id": 1, "title": "商品1", "content": "12345"},
            {"id": 2, "title": "商品2", "content": "abcde"}
        ]
    }
    
  • 在文件所在目录打来终端,运行服务器

    $ json-server --watch data.json
    
    # or 指定端口号
    $ json-server --watch data.json --port 5000
    
  • 服务器运行成功后,会根据 json 文件,生成对应 RestFul 接口;这里会生成两个接口

    // 接口一:
    http://localhost:5000/user
    
    // 接口二:
    http://localhost:5000/list
    

RestFul 接口:指的是对同一个接口地址,可以进行 get、post、put、delete 四种方式的请求,从而达到对数据的增删改查操作。

// get 请求  获取数据
axios.get('http://localhost:5000/user').then(res => {
 console.log(res)
})

// post 请求  提交数据
axios.post('http://localhost:5000/user', {
 username: '王五',
 password: 'abc789'
}).then(res => {
 console.log(res)
})

// put 请求  更新数据
axios.put('http://localhost:5000/user/1', {
 username: '张三'
 password: '123456'
}).then(res => {
 console.log(res)
})

// delete 请求  删除数据
axios.delete('http://localhost:5000/user/1').then(res => {
 console.log(res)
})

学习更多

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值