最近正好用Taro框架开发小程序,记录一下网络请求封装,结合网上前辈思路封装适合自己的。
头部请求
const interceptor = function (chain: { requestParams: any; proceed: (arg0: any) => Promise<any>; }) {
const requestParams = chain.requestParams
const { method, data, url } = requestParams
let token = Taro.getStorageSync('token') // token
requestParams.header = {
...requestParams.header,
'token': token //将token添加到头部
}
return chain.proceed(requestParams).then((res: any) => { return res })
}
// 注册头部
Taro.addInterceptor(interceptor)
请求异常处理
const request = async (method = 'GET', url: string, params: { data: any; headers: { contentType: string; }; params: any; }) => {
let contentType = params?.data ? 'application/json;charset=UTF-8' : 'application/x-www-form-urlencoded';
if (params) contentType = params?.headers?.contentType || contentType;
const option = {
method,
isShowLoading: false,
// apiConfig.baseUrl 是我自己封装环境变量 这里可以自己处理!
url: apiConfig.baseUrl + url,
data: params && (params?.data || params?.params),
header: {
'content-type': contentType,
},
success(res: { code: string; data: any; }) {
if (res.data.code ==='404') {
console.log('没有找到页面')
} else if (res.data.code === '500') {
console.log('500')
} else if (res.data.code === '401') {
console.log('401')
// 这里是处理登录 失效重新请求,根据自己的项目要求处理
// changeLogin()
} else {
console.log(res.data,'res.data')
return res.data
}
},
error(e: any) {
console.log('api', '请求接口出现问题', e);
},
fail(e: any){
Log.error(e)
Taro.navigateTo({
url: '/pages/nonetwork/nonetwork?fail='+e+''
})
}
}
const resp = await Taro.request(option);
return resp.data;
}
请求处理
export default {
get: (url: any, config: any) => {
return request('GET', url, config);
},
post: (url: any, config: any) => {
return request('POST', url, config);
},
put: (url: any, config: any) => {
return request('PUT', url, config);
},
delete: (url: any, config: any) => {
return request('DELETE', url, config);
},
patch: (url: any, config: any) => {
return request('PATCH', url, config);
},
用法
import httpService from "../servers/httpService";
// post
publish(from) {
return httpService.post('/applet/activities/publish', {
data: {...from},
});
},
// get
activitiesList(pageNo,pageSize) {
return httpService.get('/applet/all?pageNo='+pageNo+'&pageSize='+pageSize, {});
},
// put
//
注意: taro微信小程序没有fromData 上传方法可以参考:
https://github.com/zlyboy/wx-formdata.git