网络请求高级处理
请求拦截与封装
javascript
// 带拦截器的请求封装
class Request {
constructor() {
this.interceptors = {
request: (config) => config,
response: (res) => res
}
}
setInterceptors({request, response}) {
if (request) this.interceptors.request = request
if (response) this.interceptors.response = response
}
request(options) {
// 请求拦截
const config = this.interceptors.request(options)
return new Promise((resolve, reject) => {
uni.request({
...config,
success: (res) => {
// 响应拦截
const result = this.interceptors.response(res)
resolve(result)
},
fail: reject
})
})
}
}
// 使用示例
const request = new Request()
request.setInterceptors({
request: (config) => {
// 添加 token
config.header.Authorization = `Bearer ${uni.getStorageSync('token')}`
return config
},
response: (res) => {
if (res.data.code === 401) {
// 处理未授权
uni.navigateTo({url: '/pages/login'})
}
return res.data
}
})
离线缓存策略
javascript
// 结合本地存储实现请求缓存
async function requestWithCache(options, cacheTime = 300000) {
const cacheKey = options.url + JSON.stringify(options.data)
const cachedData = uni.getStorageSync(cacheKey)
// 有缓存且未过期
if (cachedData && Date.now() - cachedData.time < cacheTime) {
return cachedData.data
}
// 无缓存或已过期,发起请求
const result = await request(options)
uni.setStorageSync(cacheKey, {
data: result,
time: Date.now()
})
return result
}