uniapp 如何封装request请求
封装请求的基本思路
在Uniapp中封装request请求可以提升代码复用性、统一处理错误和简化调用。核心思路是将uni.request方法进行二次封装,加入全局配置、拦截器和错误处理逻辑。
创建请求配置文件
新建一个名为http.js的文件,存放封装的请求逻辑。定义基础URL和默认请求头:
const baseURL = 'https://api.example.com'
const defaultHeader = {
'Content-Type': 'application/json'
}
实现基础请求方法
封装核心请求函数,处理请求和响应:
function request(options) {
return new Promise((resolve, reject) => {
uni.request({
url: baseURL + options.url,
method: options.method || 'GET',
data: options.data || {},
header: Object.assign({}, defaultHeader, options.header),
success: (res) => {
if (res.statusCode === 200) {
resolve(res.data)
} else {
reject(res)
}
},
fail: (err) => {
reject(err)
}
})
})
}
添加请求拦截器
在发送请求前可添加拦截逻辑处理公共参数:
function requestWithInterceptor(options) {
const token = uni.getStorageSync('token')
if (token) {
options.header = options.header || {}
options.header.Authorization = `Bearer ${token}`
}
return request(options)
}
实现便捷方法
封装常用HTTP方法简化调用:
export default {
get(url, params) {
return requestWithInterceptor({ url, method: 'GET', data: params })
},
post(url, data) {
return requestWithInterceptor({ url, method: 'POST', data })
},
put(url, data) {
return requestWithInterceptor({ url, method: 'PUT', data })
},
delete(url, data) {
return requestWithInterceptor({ url, method: 'DELETE', data })
}
}
全局错误处理
添加统一错误处理机制:
function handleError(error) {
if (error.statusCode === 401) {
uni.navigateTo({ url: '/pages/login/login' })
}
uni.showToast({
title: error.data.message || '请求失败',
icon: 'none'
})
}
function safeRequest(options) {
return requestWithInterceptor(options).catch(handleError)
}
最终使用示例
在页面中导入并使用封装好的请求:
import http from '@/utils/http.js'
// GET请求
http.get('/user/info', { id: 123 }).then(data => {
console.log(data)
})
// POST请求
http.post('/user/create', { name: 'test' }).then(data => {
console.log(data)
})
高级扩展建议
对于更复杂的需求,可以考虑以下扩展方向:

- 添加请求缓存机制
- 实现请求重试功能
- 支持文件上传下载
- 添加请求超时控制
- 集成TypeScript类型定义





