uniapp 如何封装request请求
封装 request 请求的核心思路
在 UniApp 中封装请求通常基于 uni.request,通过统一处理 URL、参数、header 和拦截逻辑提升代码复用性。以下是一个完整封装方案:
创建基础请求模块
新建 utils/request.js 文件,实现基础封装:
const BASE_URL = 'https://your-api-domain.com/api'
const request = (options) => {
return new Promise((resolve, reject) => {
uni.request({
url: BASE_URL + options.url,
method: options.method || 'GET',
data: options.data || {},
header: {
'Content-Type': 'application/json',
...options.header
},
success: (res) => {
if (res.statusCode === 200) {
resolve(res.data)
} else {
reject(res.data)
}
},
fail: (err) => {
reject(err)
}
})
})
}
添加请求拦截器
在发出请求前统一处理 token 等认证信息:
const getToken = () => uni.getStorageSync('token')
const requestWithInterceptor = (options) => {
const token = getToken()
if (token) {
options.header = {
...options.header,
'Authorization': `Bearer ${token}`
}
}
return request(options)
}
实现响应拦截器
处理通用响应逻辑,如 token 过期:
const handleResponse = (response) => {
if (response.code === 401) {
uni.navigateTo({ url: '/pages/login/login' })
return Promise.reject(response)
}
return response.data
}
const enhancedRequest = async (options) => {
try {
const res = await requestWithInterceptor(options)
return handleResponse(res)
} catch (error) {
uni.showToast({ title: error.message, icon: 'none' })
throw error
}
}
按业务模块封装 API
创建 api/user.js 组织具体接口:
import { enhancedRequest } from '../utils/request'
export const login = (data) => {
return enhancedRequest({
url: '/user/login',
method: 'POST',
data
})
}
export const getUserInfo = () => {
return enhancedRequest({
url: '/user/info',
method: 'GET'
})
}
全局挂载与使用
在 main.js 中挂载到 Vue 原型:
import * as api from './utils/api'
Vue.prototype.$api = api
组件内调用方式:
export default {
methods: {
async fetchData() {
try {
const res = await this.$api.getUserInfo()
console.log(res)
} catch (error) {
console.error(error)
}
}
}
}
高级功能扩展
-
取消请求:使用
AbortControllerconst controller = new AbortController() uni.request({ signal: controller.signal }) // 取消请求 controller.abort() -
文件上传:封装
uni.uploadFileconst uploadFile = (filePath) => { return uni.uploadFile({ url: BASE_URL + '/upload', filePath, name: 'file', header: { 'Authorization': getToken() } }) } -
请求重试:对失败请求自动重试
const retryRequest = (options, retries = 3) => { return enhancedRequest(options).catch(err => { return retries > 0 ? retryRequest(options, retries - 1) : Promise.reject(err) }) }
这种封装方式实现了以下特性:
- 统一的 BASE_URL 配置
- 自动携带身份验证 token
- 全局错误处理和提示
- 业务逻辑与网络请求分离
- 支持扩展高级功能







