TypechoJoeTheme

至尊技术网

统计
登录
用户名
密码

uni-app网络请求拦截器配置与全局错误处理实战指南

2025-07-13
/
0 评论
/
2 阅读
/
正在检测是否收录...
07/13


一、为什么需要请求拦截器?

在uni-app开发中,每次网络请求都需要处理以下共性需求:
1. 自动携带用户token
2. API基础路径动态配置
3. 请求/响应数据格式化
4. HTTP状态码统一拦截

通过拦截器(interceptor)可将这些逻辑集中管理,避免在每个请求中重复编写。我们以uni-app内置的uni.request为基础进行改造。

二、基础拦截器实现

javascript
// utils/http.js
const BASE_URL = 'https://api.yourservice.com/v1'

const http = {
interceptor: { request(config) { // 请求前处理 config.header = config.header || {} if (uni.getStorageSync('token')) { config.header.Authorization = Bearer ${uni.getStorageSync('token')} } return config }, response(res) { // 响应后处理 return res.data } }, request(config) { config = this.interceptor.request(config)
return new Promise((resolve, reject) => {
uni.request({
url: BASEURL + config.url, method: config.method || 'GET', data: config.data, header: config.header, success: (res) => { res = this.interceptor.response(res)
resolve(res)
},
fail: reject
})
})
}
}

三、高级错误处理机制

实际项目需要区分以下错误类型:
1. 网络层错误(无响应)
2. HTTP状态码错误(4xx/5xx)
3. 业务逻辑错误(接口返回自定义错误码)

改进后的拦截器:

javascript
// 响应拦截器增强版
response(res) {
if (res.statusCode !== 200) {
const errorMap = {
401: '请重新登录',
403: '没有访问权限',
500: '服务器开小差了'
}
uni.showToast({
title: errorMap[res.statusCode] || 网络错误: ${res.statusCode},
icon: 'none'
})
return Promise.reject(res)
}

// 业务自定义错误码处理
if (res.data.code && res.data.code !== 0) {
uni.showToast({
title: res.data.message || '操作失败',
icon: 'none'
})
return Promise.reject(res.data)
}

return res.data
}

四、实战技巧与避坑指南

  1. Token过期处理
    javascript // 在响应拦截器中添加 if (res.statusCode === 401) { uni.navigateTo({ url: '/pages/login/index' }) uni.removeStorageSync('token') }

  2. 请求重试机制
    javascript const retryRequest = (config, times = 3) => { return http.request(config).catch(err => { return times > 1 ? retryRequest(config, times - 1) : Promise.reject(err) }) }

  3. 多环境配置
    javascript // 通过process.env.NODE_ENV识别环境 const BASE_URL = { development: 'https://dev.api.com', production: 'https://api.yourservice.com' }[process.env.NODE_ENV]

五、TypeScript强化版

对于TS项目,建议定义类型约束:

typescript
interface RequestConfig {
url: string
method?: 'GET' | 'POST' | 'PUT' | 'DELETE'
data?: any
header?: Record<string, string>
}

interface ResponseData {
code: number
data: T
message?: string
}

六、性能优化建议

  1. 使用uni.addInterceptor全局拦截uni-api(需HBuilderX 3.1.0+)
  2. 对GET请求开启本地缓存(设置enableCache: true
  3. 长时间未响应的请求自动取消(配合AbortController


总结:良好的请求拦截设计能让项目拥有:
- 统一的错误处理流程
- 自动化的鉴权管理
- 可维护的API层代码
- 更好的开发体验

建议根据项目实际情况调整文中方案,复杂项目可考虑移植axios核心拦截器逻辑到uni-app环境。

HTTP状态码uni-app拦截器axios适配请求封装错误统一处理
朗读
赞(0)
版权属于:

至尊技术网

本文链接:

https://www.zzwws.cn/archives/32646/(转载时请注明本文出处及文章链接)

评论 (0)