3.fetch请求
leezozz 9/12/2023 html
# 原生fetch请求
# get请求
fetch('url')
.then(response => response.json())
.then(json => console.log(json))
.catch(err => console.log('Request Failed', err));
1
2
3
4
2
3
4
// 使用promise改写
async function getData() {
let url = 'xxxurl'
try {
const res = await fetch(url)
return await res.json() // 请求 JSON 数据
} catch(error) {
console.log('error', error)
}
}
getData().then((response) => {
console.log('response', response)
})
1
2
3
4
5
6
7
8
9
10
11
12
13
14
2
3
4
5
6
7
8
9
10
11
12
13
14
- response.json() 返回一个解析为 JSON 对象的 promise;
- response.text() 返回一个解析为文本内容的 promise;
- response.formData 返回一个解析为 FormData 对象的 promise;
- response.blob() 返回一个解析为 Blog 的 promise;
- response.arrayBuffer() 返回一个解析为 ArrayBuffer 的 promise
# post请求
const getApi = () => {
fetch('url', {
method: 'post',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
testInfo: 'xxx' // 测试数据
})
}).then(response => {
response.json()
}).then(response => {
console.log('response', response)
}).catch(error => {
console.log()
})
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17