通常在项目中以插件的形引入axios,或者在uniapp中使用官方提供的uni.request就可以很方便的在页面中发送请求,直接在页面内使用原生模块提供的方法,可能会产生以下缺点
- 有可能大量涉及到各种传参,请求相关的代码,使得代码难以维护,
- 其次我们可能需要对不同的请求控制请求头,添加错误处理动画等更多扩展功能就需要对原有的通用请求在进行一层包装使得请求更加符合业务
- 当页面中请求的url有很多不一样的话还需要对请求地址进行分模块的管理
因为在实际项目中涉及到请求地址很多且不同的场景比较少,所以暂时只对接口进行两次封装
- 封装通用请求(给原有方法添加业务所需内容加载动画,请求头的统一配置,错误处理)
- 实例化通用请求,按照业务模块划分,将某一业务模块下所有页面的请求放到一个文件中
目录
在src目录下新建api文件夹,新建request.js(通用请求) 文件 和module1.js(统一业务模块用到的请求) 文件
通用请求的封装
因为是通用请求,所以此处的代码思路就是,
- 先将原生请求放到一个promise实例中,
- 根据需要配置请求头
- 添加加载动画
- 在success中对请求结果进行检查,resolve请求结果,或者提示服务器抛出的错误信息
// 更加通用的请求封装
export const commonRequest = (url: string, data: any,method:string='GET') => {
var promise: any = new Promise((resolve: any, reject: any) => {
const timestamp: any = new Date().getTime();
const headerTrue: any = {
"Content-Type": "application/json;charset=UTF-8",
timestamp: timestamp,
}
uni.showLoading({
title: "加载中…",
});
uni.request({
header:headerTrue,
url:'https://www.fastmock.site/mock/7b1c3934b8c86bd7f3412016350cfa22/lyt'+url,
data,
// @ts-ignore
method,
success:function (res:any){
uni.hideLoading()
if(res.data.code===0){
resolve(res.data)
}else{
showError(res)
}
},
fail: function(e: any) {
uni.hideLoading();
uni.showModal({
content: `查询失败,错误信息为:${e.errMsg}`,
showCancel: false,
});
console.log(e)
reject("网络出错");
},
complete:()=>{
uni.hideLoading();
}
})
})
return promise;
};
const showError = (res) => {
console.log('错误处理了s'+res.data.code)
// let that = this
if (res) {
/*console.log("------异常响应------", token)*/
console.log("------异常响应------", res.data.code)
console.log(typeof res.data.code)
switch (res.data.code) {
case 403:
uni.showToast({
title: '拒绝访问',
icon: 'none',
duration: 4000
});
break
case 500:
if (res.data.code === 100) {
uni.showModal({
title: '登录已过期',
content: '很抱歉,登录已过期,请重新登录',
confirmText: '重新登录',
success: function (res) {
if (res.confirm) {
//去我的页面登录
uni.navigateTo({
url: '/pages/login/login'
});
} else if (res.cancel) {
console.log('用户点击取消');
}
}
})
// update-end- --- author:scott ------ date:20190225 ---- for:Token失效采用弹框模式,不直接跳转----
}
break
case 404:
uni.showToast({
title: '很抱歉,资源未找到!',
icon: 'none',
duration: 4000
});
break
case 504:
uni.showToast({
title: '网络超时',
icon: 'none',
duration: 2000
});
break
case 502:
uni.showToast({
title: '服务器异常',
icon: 'none',
duration: 2000
});
break
case 401:
uni.showToast({
title: '未授权,请重新登录',
icon: 'none',
duration: 4000
});
/*if (token == '') {
setTimeout(() => {
//去我的页面登录
uni.switchTab({
url: '/pages/views/mine'
});
}, 1500)
}*/
break
default:
uni.showToast({
title: res.data.message,
icon: 'none',
duration: 4000
});
break
}
}
}
业务模块下的请求
此处就是给使用通用请求来发送特定的业务请求
import {commonRequest} from './requst'
export function List(type,pageNumber=1,pageSize=10){
return commonRequest('/msgList',{
pageSize,
pageNumber
})
}
网友评论