UTS封装uni.request请求拦截器
本文最后更新于 天前,文中涉及的版本或信息可能已发生变动,请结合最新文档参考。
UTS封装请求拦截器主要就是数据类型的问题
- 简单封装示例:每次请求在请求头中携带设备信息
typescript
export type RequestParams = {
url: string;
method: RequestMethod;
data?: string;
header?: UTSJSONObject;
timeout?: number;
sslVerify?: boolean;
withCredentials?: boolean;
firstIpv4?: boolean;
}
export type RequestRoot = {
code: number;
msg: string;
data?: any
}
export type RequestRes = {
data?: any;
error?: string;
}
// 获取系统信息
export const getSystemInfo = (): string => {
const system = uni.getSystemInfoSync()
// 返回app信息,依次为appid,系统名称,系统版本,app版本,设备id,使用____分割
return system.appId + "____" + system.osName + "____" + system.osVersion + "____" + system.appVersionCode + "____" + system.deviceId
}
// 发送请求并携带设备信息
export const sendRequest = (options: RequestParams): Promise<RequestRes> => {
let info = getSystemInfo();
let header = {}
if (options.header != null) {
header = UTSJSONObject.assign(options.header as UTSJSONObject, { app: info })
}else {
header = UTSJSONObject.assign(header, { app: info })
}
// 返回一个Promise
return new Promise((resolve, reject) => {
uni.request<RequestRoot>({
// ...options, // 展开其他请求配置
url: options.url,
method: options.method,
data: options.data ?? "",
header: header,
timeout: options.timeout ?? 6000,
sslVerify: options.sslVerify ?? true,
withCredentials: options.withCredentials ?? false,
firstIpv4: options.firstIpv4 ?? false,
success: (res) => {
const data = res.data as RequestRoot
if(data.code == 200) {
// 在请求成功时解析Promise
resolve({
data: data.data
} as RequestRes)
}else {
uni.showToast({
title: data.msg,
icon: "error"
})
reject({
error: data['msg'] as string
} as RequestRes)
}
},
fail: (err) => {
uni.showToast({
title: err.errMsg,
icon: "error"
})
// 在请求失败时拒绝Promise
reject({
error: err.errMsg as string
} as RequestRes)
}
} as RequestOptions<any>);
});
}
- 使用示例
typescript
// 导入封装的函数
import { sendRequest } from "@/common/request.uts"
// 定义存储的变量
// 1. 数组
const list = ref<UTSJSONObject[]>([])
// 2. 对象
// const list = ref<UTSJSONObject>({})
// 请求示例:使用Promise的方式调用sendRequest函数
sendRequest({
url: 'https://api.example.com/data',
method: 'GET'
}).then(res => {
// 处理请求成功的结果
list.value = res.data as UTSJSONObject[] // 数组,对应的存储数组的变量
// list.value = res.data as UTSJSONObject // 对象,对应的存储对象的变量
console.log('处理结果:', data.value);
}).catch(err => {
// 处理请求失败的情况
console.error('请求失败:', err);
})
- 在模板中使用示例
{message type="warning" content="注意使用变量中数据的方法只能为下标[""]方法,.操作符不可以,会报错"/}
html
<view v-for="item in noticeList" :key="item['id']">
<image mode="widthFix" :src="item['image']"></image>
<view>
<text>{{ item['title'] }}</text>
<text>{{ item['sort'] }}</text>
</view>
</view>
说明: 因为书写习惯原因,我自己的所有后端返回数据均为json,返回对象参数如下
| 参数 | 描述 | 示例 |
|---|---|---|
| code | 错误码 | 200: 成功, 400: 失败, 或其他 |
| msg | 请求结果说明 | 请求成功/请求失败等 |
| data | 请求返回的结果 | json数组/对象 |
示例如下:
- data为数组
json
{
code: 200,
msg: "请求成功",
data: []
}
- data为对象
json
{
code: 200,
msg: "请求成功",
data: {}
}
对应封装的请求中的自定义类型RootRes(request.uts文件中)
本文作者:
KongHen02
版权声明:
本博客所有原创文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议,转载请注明出处。
评论