//创建一个序列化函数,通过遍历对象,将对象的属性值放进数组
function serialize(params) {
let arr = []
for (let key in params) {
arr.push(`${key}=${params[key]}`)
}
return "?" + arr.join('&')
}
var request = {
get(url, config = {}) {
let queryParams = ""
if (config.params) {
queryParams = serialize(config.params)
}
return fetch(url + queryParams, {
method: "GET"
}).then((res) => {
if (res.status >= 200 && res.status < 300) {
return res.json()
}
return Promise.reject({
code: res.status,
msg: res.statusText
})
})
},
post(url, data) {
return fetch(url, {
method: "POST",
headers: {
"Content-type": "application/json"
},
body: JSON.stringify(data)
}).then(res => {
if (res.status >= 200 && res.status < 300) {
return res.json()
}
return Promise.reject({
code: res.status,
msg: res.statusText
})
})
},
patch(url, data) {
return fetch(url, {
method: "PATCH",
headers: {
"Content-type": "application/json"
},
body: JSON.stringify(data)
}).then(res => {
if (res.status >= 200 && res.status < 300) {
return res.json()
}
return Promise.reject({
code: res.status,
msg: res.statusText
})
})
},
dalete(url, config = {}) {
let queryParams = ""
if (config.params) {
queryParams = serialize(config.params)
}
return fetch(url + queryParams, {
method: "DELETE"
}).then((res) => {
if (res.status >= 200 && res.status < 300) {
return res.json()
}
return Promise.reject({
code: res.status,
msg: res.statusText
})
})
}
}
封装一个request函数(使用fetch)
最新推荐文章于 2023-01-02 23:24:25 发布