json-server 增删查改 快速上手

参考文档 http://t.csdnimg.cn/gGjFJ

一、json-server 安装,创建数据,启动

安装 json-server

npm install json-server

创建json文件

创建 db.json 来存储数据

{
  "users": [
    {
      "id": 1,
      "name": "John",
      "age": 18
    },
    {
      "id": 2,
      "name": "Anna",
      "age": 20
    },
    {
      "id": 3,
      "name": "Elsa",
      "age": 20
    },
    {
      "id": 4,
      "name": "Olaf",
      "age": 5
    },
    {
      "id": 5,
      "name": "Lisa",
      "age": 30
    }
  ]
}

启动 json-server

--port 8080 修改端口号为8080, 默认3000

json-server --watch db.json --port 8080

访问网址 http://localhost:8080

启动成功如图所示

访问网址 http://localhost:8080/users

好,我们的第一阶段就成功了

二、增删查改

我们需要用到apifox或者postman来做接口调试,我这边使用apifox

查看/获取

获取所有用户

新建一个接口,使用GET方法,访问 http://localhost:8080/users

获取个人用户信息

我们通过访问 http://localhost:8080/users/1 来访问id为1的用户个人信息

也可以通过 http://localhost:8080/users?id=1的方式访问

分页查询

通过访问 http://localhost:8080/users?_page=1&_limit=2 来访问第一页的数据(每页展示2条)

模糊查询

通过姓名查询用户 

http://localhost:8080/users?name=Lisa

通过姓名模糊查询用户 (在字段后面添加like)

http://localhost:8080/users?name_like=Lisa

增加

POST http://localhost:8080/users

如果没有说明id,json-server会自动补上

(这个地方不应该是username,应该是name,我忘记了,数据库里面没有username这个字段)

修改

注意:需要在路由上说明要修改的用户的id(不能在响应体里写id)

删除

DELETE http://localhost:8080/users/1

json-server是一个可以快速创建RESTful API的工具,可以用来模拟后端API接口。以下是在json-server中进行增删改查的代码示例。 1. 安装json-server ``` npm install json-server -g ``` 2. 创建一个JSON数据文件db.json,例如: ``` { "users": [ { "id": 1, "name": "Tom", "age": 20 }, { "id": 2, "name": "Jerry", "age": 22 } ] } ``` 3. 启动json-server ``` json-server db.json ``` 4. 在Vue组件中使用axios库来发起HTTP请求,例如: ``` import axios from 'axios' export default { data() { return { users: [] } }, created() { this.getUsers() }, methods: { getUsers() { axios.get('http://localhost:3000/users') .then(response => { this.users = response.data }) .catch(error => { console.log(error) }) }, addUser() { axios.post('http://localhost:3000/users', { name: "Jack", age: 25 }) .then(response => { this.getUsers() }) .catch(error => { console.log(error) }) }, updateUser(id) { axios.put(`http://localhost:3000/users/${id}`, { name: "John", age: 30 }) .then(response => { this.getUsers() }) .catch(error => { console.log(error) }) }, deleteUser(id) { axios.delete(`http://localhost:3000/users/${id}`) .then(response => { this.getUsers() }) .catch(error => { console.log(error) }) } } } ``` 在这个代码示例中,getUsers方法用来获取所有用户数据,addUser方法用来添加新用户,updateUser方法用来更新指定id的用户数据,deleteUser方法用来删除指定id的用户数据。 需要注意的是,axios发送的请求的URL地址应该与json-server启动的端口号一致。在本例中,json-server启动的端口号为3000。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值