0%

常见的网络请求方式

安装json-server

用npm安装json-server可以创建一个简单的调用后端数据调用接口

1
npm install json-server -g

建立一个json文件,如react-db.json (注意:json文件里面不要写注释,注意格式,不要写多余的逗号,否则运行的时候会报错

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
{
"products": [
{
"id": 1,
"productName": "iPhone",
"price": 8900,
"quantity": 1
},
{
"id": 2,
"productName": "iPad Pro",
"price": 124000,
"quantity": 3
},
{
"id": 3,
"productName": "荣耀p30",
"price": 4000,
"quantity": 3
},
{
"id": 4,
"productName": "小米",
"price": 3000,
"quantity": 8
},
{
"id": 5,
"productName": "iPad 11",
"price": 3000,
"quantity": 34
}
]
}

执行以下指令,将react-db.json的数据上传到json-server

1
json-server react-db.json --watch --port=5000

这样就可以生成对应的API了

GET请求

向服务器获取数据

1
2
3
4
5
6
7
8
9
10
11
12
13
componentDidMount = async () => {
const response = await fetch('http://localhost:5000/customers', {
method: 'GET',
})
if (response.ok) {
const body = await response.json()
if (body) {
this.setState({ customers: body, customersCount: body.length})
} else {
return 'Error:' + response.status
}
}
}

POST请求

向服务器发送数据,比如说注册用户信息

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
  //以下可实现点击提交按钮注册新用户并将页面跳转到顾客列表页面
onSaveClick = async (event) => {
event.preventDefault()
//获取用户填写的信息
var newcustomer = {
name: this.state.name,
address: { city: this.state.city },
phone: this.state.phone,
photo: this.state.photo,
}

var response = await fetch('http://localhost:5000/customers ',
{method:"POST",
body: JSON.stringify(newcustomer),
headers: {"Content-type": "application/json"}
})
var body =await response.json()//请求发送成功后跳转页面
if (body){
history.replace('/customers')
}
}

PUT请求

向服务器发送更改后的信息,比如修改用户信息,链接要带上具体的id,表明更新的是哪一条用户数据

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
onSaveClick = async (event) => {
event.preventDefault()
var newcustomer = {
name: this.state.name,
address: { city: this.state.city },
phone: this.state.phone,
photo: this.state.photo,
}
var id = this.props.match.params.id
var response = await fetch(`http://localhost:5000/customers/${id} `, {
method: 'PUT',
body: JSON.stringify(newcustomer),
headers: { 'Content-type': 'application/json' },
})
var body = await response.json()
if (body) {
history.replace('/customers')
}
}

DELETE请求

删除服务器数据。和PUT一样,也要带上具体的id,表明删除的是哪一条数据,注意数据删除是删除数据库中的数据,本地数据还是没有更新的,此时要用setState更新下状态,更新后的状态filter出不包含已删除的数据(用id做判断))

1
2
3
4
5
6
7
8
9
10
11
12
onClickDelete =async (id) =>{
if (window.confirm("确定要删除吗?")) {
var response = await fetch(`http://localhost:5000/customers/${id}`, {method: "DELETE"})
if (response.ok){
let allcustomers = [...this.state.customers];
console.log(allcustomers);
allcustomers = allcustomers.filter(cust => {return cust.id !== id})
this.setState({customers: allcustomers})
}
}
}