uniapp请求库封装
uniapp 请求库封装方法
uniapp 的请求功能基于 uni.request,但直接使用可能不够灵活。通过封装可以统一处理请求参数、响应数据、错误处理等逻辑,提升开发效率和代码可维护性。
基础封装示例
创建一个 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)
}
})
})
}
export default request
添加拦截器功能
扩展基础封装,加入请求和响应拦截器:
const interceptors = {
request: [],
response: []
}
const addRequestInterceptor = (callback) => {
interceptors.request.push(callback)
}
const addResponseInterceptor = (callback) => {
interceptors.response.push(callback)
}
const runInterceptors = async (type, value) => {
for (const interceptor of interceptors[type]) {
value = await interceptor(value)
}
return value
}
const enhancedRequest = async (options) => {
try {
options = await runInterceptors('request', options)
const response = await request(options)
return await runInterceptors('response', response)
} catch (error) {
throw error
}
}
export { enhancedRequest as request, addRequestInterceptor, addResponseInterceptor }
使用示例
在页面或组件中导入并使用封装后的请求库:
import { request, addRequestInterceptor, addResponseInterceptor } from '@/utils/request'
// 添加请求拦截器
addRequestInterceptor((config) => {
const token = uni.getStorageSync('token')
if (token) {
config.header = {
...config.header,
'Authorization': `Bearer ${token}`
}
}
return config
})
// 添加响应拦截器
addResponseInterceptor((response) => {
if (response.code !== 0) {
uni.showToast({
title: response.message || '请求失败',
icon: 'none'
})
throw new Error(response.message)
}
return response.data
})
// 发起请求
const fetchData = async () => {
try {
const result = await request({
url: '/user/info',
method: 'GET'
})
console.log(result)
} catch (error) {
console.error(error)
}
}
高级功能扩展
针对更复杂的场景,可以进一步扩展封装:
// 超时设置
const requestWithTimeout = (options, timeout = 10000) => {
return Promise.race([
request(options),
new Promise((_, reject) => {
setTimeout(() => {
reject(new Error('请求超时'))
}, timeout)
})
])
}
// 取消请求
const createCancelToken = () => {
let cancel
const token = new Promise((resolve) => {
cancel = resolve
})
return { token, cancel }
}
// 并发控制
const createRequestQueue = (maxConcurrent = 5) => {
const queue = []
let running = 0
const runNext = () => {
if (running >= maxConcurrent || queue.length === 0) return
running++
const { task, resolve, reject } = queue.shift()
task()
.then(resolve)
.catch(reject)
.finally(() => {
running--
runNext()
})
}
return (task) => {
return new Promise((resolve, reject) => {
queue.push({ task, resolve, reject })
runNext()
})
}
}
类型提示(TypeScript)
如果使用 TypeScript,可以添加类型定义:
interface RequestOptions {
url: string
method?: 'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH'
data?: any
header?: Record<string, string>
}
interface ResponseData<T = any> {
code: number
message: string
data: T
}
type Interceptor<T> = (value: T) => T | Promise<T>
const request = <T>(options: RequestOptions): Promise<ResponseData<T>> => {
// 实现同上
}
通过以上封装,可以构建一个功能完善、易于维护的 uniapp 请求库,满足各种业务场景需求。







