Fetch简单封装

不多逼逼,直接上代码

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
35
36
37
38
39
40
41
42
43
44
45
function request(option = {
method: 'GET',
formData: false
}) {
let url = option.url
if (option.param) {
url = `${url}?${qs(option.param)}`
}
function qs(data, flag) {
const typeObj = (obj) => Object.prototype.toString.call(obj).slice(8, -1) === 'Object'
const typeArr = (obj) => Object.prototype.toString.call(obj).slice(8, -1) === 'Array'
var str = '', originData, encodeData;
for (var i in data) {
if (data.hasOwnProperty(i)) {
originData = data[i]
if (typeObj(originData) || typeArr(originData)) {
str += qs(originData, i)
} else {
encodeData = encodeURIComponent(originData)
if (typeObj(data) && flag) {
str += `${flag}[${i}]=${encodeData}&`
} else if (typeArr(data) && flag) {
str += `${flag}[${i}]=${encodeData}&`
// str += `${flag}=${encodeData}&`
} else {
if (str.length > 0 && str[str.length - 1] !== '&') str += '&';
str += `${i}=${encodeData}&`
}
}
}
}
return str[str.length - 1] === '&' ? str.slice(0, -1) : str
}
return fetch(url, {
method: option.method,
headers: option.formData ? undefined : {
'Content-Type': 'application/json',
},
body: option.formData ? Object.keys(option.data).reduce((ret, val) => {
ret.append(val, option.data[val])
return ret
}, new FormData()) : JSON.stringify(option.data),
}).then(response => response.json())
}

用法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
// get请求
await request({
url: 'https://netease-cloud-music-api-dv7rufaa3-vearvip.vercel.app/search',
method: 'GET',
param: {
keywords: '海阔天空'
}
})
// post请求
// formData自行决定是否开启,默认不开启
await request({
url: 'https://netease-cloud-music-api-dv7rufaa3-vearvip.vercel.app/search',
method: 'POST',
formData: true,
data: {
keywords: '海阔天空'
}
})
作者

vear

发布于

2022-01-17

更新于

2022-01-18

许可协议

评论