json-server增删改查代码
时间: 2023-12-31 08:04:22 浏览: 32
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。