json-server增删改查
时间: 2023-05-28 08:04:59 浏览: 62
JSON Server 是一个快速的内存数据库,可以用来快速创建和测试 RESTful API。在 JSON Server 中,可以使用以下 HTTP 方法进行增删改查:
1. GET 方法用于获取数据。例如,使用以下命令获取所有数据:
```
GET /data
```
2. POST 方法用于创建数据。例如,使用以下命令创建一条新的数据:
```
POST /data
```
然后在请求体中提供数据。
3. PUT 方法用于更新数据。例如,使用以下命令更新一条数据:
```
PUT /data/1
```
然后在请求体中提供新的数据。
4. DELETE 方法用于删除数据。例如,使用以下命令删除一条数据:
```
DELETE /data/1
```
这将删除 ID 为 1 的数据。
在 JSON Server 中,可以使用以下命令启动服务器:
```
json-server --watch db.json
```
这将启动一个服务器,监听端口为 3000,并使用 db.json 文件作为数据源。在启动服务器后,可以使用上述 HTTP 方法进行增删改查操作。
相关问题
json-server增删改查代码
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。
json-server
json-server是一个用于快速创建RESTful API的工具,它可以让您在几分钟内创建一个具有完整CRUD功能的API。它的实现方式是将一个JSON文件作为数据库,通过HTTP请求对其进行增删改查操作。您可以通过npm安装json-server,然后在命令行中运行以下命令来启动它:
```
json-server --watch db.json
```
其中,`db.json`是您的JSON文件,您可以根据需要进行修改。启动后,您可以通过访问`http://localhost:3000`来访问API。json-server支持多种HTTP请求方法,例如GET、POST、PUT、DELETE等,您可以通过访问`http://localhost:3000`来查看它所支持的所有请求。