几天才想起来前一段时间fetch的简单封装,今天简单记一下,话不多说直接上代码(结合了typescript不过不需要直接去除类型就行)
const url_base: string = "http://127.0.0.1:9097"
export async function request(params: API.RequestAPI) {
let url: string = url_base + params?.url
const method: string = params?.method
const header: any = params?.header
const data: any = params?.data
const get_params: any = params?.params
const get_params_list: Array<any> = []
if (get_params) {
for (const item in get_params) {
get_params_list.push(item + "=" + get_params[item])
}
if (url.search(/\?/) === -1) {
url += ‘?‘ + get_params_list.join(‘&‘)
} else {
url += ‘&‘ + get_params_list.join(‘&‘)
}
}
const headers = {
‘Content-Type‘: ‘application/json‘,
"Content-type": "application/x-www-form-urlencoded; charset=UTF-8",
...header
}
return await fetch(url, {
method: method,
// body: JSON.stringify(data),
headers: new Headers(headers),
mode: ‘cors‘,
credentials: ‘omit‘,
...data
})
.then(res => { return res.json() })
// .then(res => res.status)
// .then(response => response.json())
.catch(error => { return error })
}
使用,
// api
import { request } from "@/utils/request"
export async function getArticleList(params: any) {
return request({
url: ‘/getArticle/list‘,
method: ‘GET‘,
params
})
}
//tsx -->vue
await getArticleList(params).then(res => {
this.article_list = res?.data
console.log(res?.data)
})
.catch(err => {
this.$message({
type: ‘success‘,
message: "请求失败"
})
console.log(err)
})
直接也会第一次封装,可能好多自己也都没考虑到,简单记录一下