作者:前端小王hs
阿里云社區(qū)博客專家/清華大學(xué)出版社簽約作者?/CSDN百萬訪問博主/B站千粉前端up主
封裝攔截器
uniapp
的封裝邏輯不同于Vue3
項目中直接使用axios.create()
方法創(chuàng)建實例(在create
方法中寫入請求的地址、請求頭、超時等內(nèi)容),代碼如下:
const instance = axios.create({
// 后端url地址
baseURL: import.meta.env.VITE_API_BASEURL,
timeout: 6000, //設(shè)置超時
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
});
PS:上述代碼來自博主在B站的Vue3全家桶+MySQL+Express全棧實戰(zhàn)項目源碼
在uniapp
中,需要使用到一個官方的API
即uni.addInterceptor(STRING, OBJECT)
,這是一個用于攔截作用的API
,在規(guī)范開發(fā)的過程中,會在請求之前為請求的內(nèi)容拼接url
、超時和請求頭等信息,這一點在官方文檔API
的基礎(chǔ)攔截器一文中詳細(xì)的示例,代碼如下:
uni.addInterceptor('request', {
invoke(args) {
// request 觸發(fā)前拼接 url
args.url = 'https://www.example.com/'+args.url
},
success(args) {
// 請求成功后,修改code值為1
args.data.code = 1
},
fail(err) {
console.log('interceptor-fail',err)
},
complete(res) {
console.log('interceptor-complete',res)
}
})
所以可以封裝一個攔截器的配置項,為所有的uni.request
添加請求前置信息,代碼如下:
const baseURL = import.meta.env.VITE_API_BASEURL
// 添加攔截器
const httpInterceptor = {
// 攔截前觸發(fā)
invoke(options: UniApp.RequestOptions) {
// 假設(shè)開頭為非http的請求url地址
if (!options.url.startsWith('http')) {
options.url = baseURL + options.url
}
// 請求超時
options.timeout = 6000
options.header = {
...options.header,
// 自定義標(biāo)識符,用于后端區(qū)分app、后臺或其他渠道請求
'source-client': 'app',
}
// 添加 token 請求頭標(biāo)識
const token = uni.getStorage('token')
if (token) {
options.header.Authorization = token
}
},
}
uni.addInterceptor('request', httpInterceptor)
這是一段萬能的uniapp
封裝攔截器代碼,讀者可收藏此文章粘貼即用,下同
封裝uni.request
這里的封裝,參考了axios
返回promise
對象的實現(xiàn)邏輯,在接口中return
一個promise
對象,便于在實際環(huán)境中更好的獲取數(shù)據(jù)以及進一步處理數(shù)據(jù),代碼如下:文章來源:http://www.zghlxwxcb.cn/news/detail-855321.html
type Data<T> = {
// 后端返回的通用響應(yīng)結(jié)構(gòu)
statusCode: string
msg: string
result: T
}
// UniApp.RequestOptions為配置網(wǎng)絡(luò)請求的選項
// 這里使用了泛型,便于自定義響應(yīng)結(jié)構(gòu)
export const http = <T>(options: UniApp.RequestOptions) => {
return new Promise<Data<T>>((resolve, reject) => {
uni.request({
// 攔截器配置內(nèi)容
...options,
success(res) {
// 成功響應(yīng)
handleResponse(res, resolve, reject);
},
fail(err) {
handleError(err, reject);
},
});
};
};
// resolve和reject不返回任何值,但通知promise更改狀態(tài)
const handleResponse = <T>(res: any, resolve: (value: Data<T>) => void, reject: (reason?: any) => void) => {
// 分離了驗證狀態(tài)碼邏輯
if (isSuccessStatusCode(res.statusCode)) {
resolve(res.data as Data<T>);
// 登錄失敗
} else if (res.statusCode === 401) {
// 假設(shè) clearUserInfo 是清除用戶信息的函數(shù)
clearUserInfo();
// 跳轉(zhuǎn)至登錄頁面
uni.navigateTo({ url: '/pages/login/index' });
reject(res);
} else {
// 分離了報錯狀態(tài)碼邏輯
showErrorToast(res.data as Data<T>);
reject(res);
}
};
const handleError = (err: any, reject: (reason?: any) => void) => {
uni.showToast({
icon: 'none',
title: '網(wǎng)絡(luò)可能開小差了~',
});
reject(err);
};
const isSuccessStatusCode = (statusCode: number) => {
return statusCode >= 200 && statusCode < 300;
};
const showErrorToast = <T>(data: Data<T>) => {
uni.showToast({
icon: 'none',
title: data.msg || '請求錯誤',
});
};
關(guān)于RequestOptions
更多的信息,可以對其ctrl+點擊
查看內(nèi)置的接口信息,如下圖所示:文章來源地址http://www.zghlxwxcb.cn/news/detail-855321.html
到了這里,關(guān)于Vue3+TS版本Uniapp:封裝uni.request請求配置的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!