更新记录
1.0.0(2025-04-07) 下载此版本
- 自动重试机制 - 遇到网络错误、超时或特定状态码时自动重试请求
- 请求优先级队列管理 - 根据优先级管理请求执行顺序
- 全局Loading动画 - 自动管理全局加载状态
- 统一错误拦截 - 集中处理错误,减少重复代码
- 请求取消支持 - 轻松取消进行中的请求
- 双模式支持 - 同时支持RESTful API和GraphQL请求
平台兼容性
HbuilderX/cli最低兼容版本 |
---|
3.96 |
uni-app
Vue2 | Vue3 |
---|---|
√ | ? |
app-vue | app-nvue | app-android | app-ios | app-harmony |
---|---|---|---|---|
? | ? | ? | ? | ? |
H5-Safari | Android Browser | 微信浏览器(Android) | QQ浏览器(Android) | Chrome | IE | Edge | Firefox | PC-Safari |
---|---|---|---|---|---|---|---|---|
? | ? | ? | ? | ? | ? | ? | ? | ? |
微信小程序 | 支付宝小程序 | 百度小程序 | 字节小程序 | QQ小程序 | 钉钉小程序 | 快手小程序 | 飞书小程序 | 京东小程序 |
---|---|---|---|---|---|---|---|---|
? | ? | ? | ? | ? | ? | ? | ? | ? |
快应用-华为 | 快应用-联盟 |
---|---|
? | ? |
uni-app x
app-android | app-ios |
---|---|
? | ? |
H5-Safari | Android Browser | 微信浏览器(Android) | QQ浏览器(Android) | Chrome | IE | Edge | Firefox | PC-Safari |
---|---|---|---|---|---|---|---|---|
? | ? | ? | ? | ? | ? | ? | ? | ? |
XL-Request 智能网络请求管理器
在线演示地址:https://xlandzxg-8gj5901i764f06f7-1308786497.tcloudbaseapp.com/index.html#/ 一个功能强大的网络请求管理工具,专为uniapp打造,提供自动重试、优先级队列、全局错误处理等高级特性。
核心功能
- 自动重试机制 - 遇到网络错误、超时或特定状态码时自动重试请求
- 请求优先级队列管理 - 根据优先级管理请求执行顺序
- 全局Loading动画 - 自动管理全局加载状态
- 统一错误拦截 - 集中处理错误,减少重复代码
- 请求取消支持 - 轻松取消进行中的请求
- 双模式支持 - 同时支持RESTful API和GraphQL请求
安装
将xl-request
组件复制到项目的components
目录下即可使用。
基本用法
基本请求
import request from '@/components/xl-request';
// GET请求
request.get('/api/users', { page: 1, limit: 10 })
.then(response => {
console.log(response.data);
})
.catch(error => {
console.error('请求失败:', error);
});
// POST请求
request.post('/api/users', {
name: '张三',
age: 30
}).then(response => {
console.log('创建成功:', response.data);
});
// PUT请求
request.put('/api/users/1', {
name: '张三修改'
});
// DELETE请求
request.delete('/api/users/1');
配置请求
request.request({
url: '/api/products',
method: 'GET',
params: { category: 'electronics' },
headers: { 'Authorization': 'Bearer token123' },
timeout: 5000,
retry: {
maxRetries: 3,
retryDelay: 1000
},
priority: 2, // 优先级:0(最高)到2(最低)
loading: true // 是否显示加载指示器
})
GraphQL请求
request.graphql({
query: `
query GetUser($id: ID!) {
user(id: $id) {
id
name
email
posts {
id
title
}
}
}
`,
variables: {
id: '123'
}
}).then(response => {
console.log('用户数据:', response.data.user);
});
取消请求
// 创建具有请求ID的请求
const requestId = 'user_data_request';
request.get('/api/users', {}, {
requestId
});
// 取消该请求
request.cancel(requestId);
// 取消所有请求
request.cancelAll('页面已离开');
高级特性
自动重试
默认情况下,XL-Request会对特定的错误自动进行重试:
- 网络错误
- 请求超时
- 特定状态码:408, 500, 502, 503, 504
可以通过配置自定义重试行为:
request.setConfig({
retry: {
maxRetries: 5, // 最大重试次数
retryDelay: 2000, // 重试延迟(毫秒)
retryableStatusCodes: [408, 500, 502, 503, 504, 429] // 可重试的状态码
}
});
请求优先级队列
XL-Request支持请求优先级,确保重要请求优先执行:
// 最高优先级请求
request.get('/api/critical-data', {}, { priority: 0 });
// 中等优先级请求(默认)
request.get('/api/regular-data');
// 低优先级请求
request.get('/api/non-critical-data', {}, { priority: 2 });
可自定义队列配置:
request.setConfig({
queue: {
maxConcurrent: 8, // 最大并发请求数
priorityLevels: 5 // 优先级级别数
}
});
全局Loading和错误处理
XL-Request自动管理全局加载状态,可通过以下方式配置:
request.setConfig({
loading: {
global: true, // 是否启用全局loading
delay: 500, // loading显示延迟(毫秒)
customLoading: (show, config) => {
// 自定义loading实现
if (show) {
uni.showLoading({ title: config.loadingText || '加载中...' });
} else {
uni.hideLoading();
}
}
},
// 自定义错误处理
errorHandler: (error, config) => {
if (error.status === 401) {
// 处理未授权错误
uni.showToast({
title: '请先登录',
icon: 'none'
});
// 跳转到登录页
uni.navigateTo({ url: '/pages/login/login' });
return Promise.reject(error);
}
if (error.status === 403) {
// 处理禁止访问错误
uni.showToast({
title: '没有权限访问',
icon: 'none'
});
return Promise.reject(error);
}
// 其他错误使用通用处理
uni.showToast({
title: error.message || '网络请求失败',
icon: 'none'
});
return Promise.reject(error);
}
});
监听请求状态
通过store可以监听和响应请求状态:
import { useRequestStore } from '@/components/xl-request/store';
export default {
setup() {
const requestStore = useRequestStore();
// 监听加载状态
watch(() => requestStore.state.loading, (loading) => {
console.log('全局加载状态:', loading);
});
// 监听错误
watch(() => requestStore.state.error, (error) => {
if (error) {
console.log('发生错误:', error);
}
});
// 获取请求统计
const stats = computed(() => requestStore.state.stats);
}
}
全局配置
可以通过setConfig
方法设置全局配置:
request.setConfig({
// 基础URL
baseURL: 'https://api.example.com',
// 超时时间
timeout: 30000,
// 默认请求头
headers: {
'Content-Type': 'application/json',
'X-Client-Version': '1.0.0'
},
// 状态码校验函数
validateStatus: (status) => status >= 200 && status < 300
});
请求拦截
如需更高级的拦截功能,可以创建自定义实例:
import { XlRequest } from '@/components/xl-request';
// 创建自定义实例
const apiClient = new XlRequest({
baseURL: 'https://api.example.com',
headers: {
'Content-Type': 'application/json'
}
});
// 添加请求修改中间件
apiClient.use({
beforeRequest: (config) => {
// 添加认证令牌
const token = uni.getStorageSync('token');
if (token) {
config.headers = {
...config.headers,
'Authorization': `Bearer ${token}`
};
}
return config;
},
afterResponse: (response) => {
// 处理响应
if (response.data && response.data.code === 0) {
return response.data.data;
}
return response;
},
onError: (error) => {
// 统一错误处理
console.error('请求错误:', error);
// 返回自定义错误
return Promise.reject(new Error('自定义错误信息'));
}
});
export default apiClient;
最佳实践
API管理模式
推荐按模块组织API请求:
// api/user.js
import request from '@/components/xl-request';
export const userApi = {
getProfile() {
return request.get('/api/user/profile');
},
updateProfile(data) {
return request.put('/api/user/profile', data);
},
login(credentials) {
return request.post('/api/auth/login', credentials);
}
};
// 使用
import { userApi } from '@/api/user';
// 组件中调用
const { data } = await userApi.getProfile();
多环境配置
结合uniapp环境变量实现多环境配置:
// 根据环境设置baseURL
let baseURL = '';
// #ifdef H5
baseURL = process.env.NODE_ENV === 'development'
? '/api'
: 'https://prod.example.com/api';
// #endif
// #ifdef MP-WEIXIN
baseURL = 'https://prod.example.com/api';
// #endif
// 初始化请求配置
request.setConfig({
baseURL
});
API参考
主要方法
方法 | 描述 | 参数 |
---|---|---|
request(config) |
发送请求 | 请求配置对象 |
get(url, params, config) |
GET请求 | URL, 查询参数, 配置 |
post(url, data, config) |
POST请求 | URL, 数据, 配置 |
put(url, data, config) |
PUT请求 | URL, 数据, 配置 |
delete(url, config) |
DELETE请求 | URL, 配置 |
graphql(options) |
GraphQL请求 | GraphQL选项 |
cancel(requestId) |
取消请求 | 请求ID |
cancelAll(reason) |
取消所有请求 | 取消原因 |
setConfig(config) |
设置配置 | 配置对象 |
setHeaders(headers) |
设置请求头 | 请求头对象 |
配置选项
选项 | 类型 | 默认值 | 描述 |
---|---|---|---|
baseURL |
String | '' |
请求的基础URL |
timeout |
Number | 60000 |
请求超时时间(毫秒) |
headers |
Object | {} |
请求头 |
retry |
Object | {maxRetries: 3, retryDelay: 1000, retryableStatusCodes: [408, 500, 502, 503, 504]} |
重试配置 |
queue |
Object | {maxConcurrent: 6, priorityLevels: 3} |
队列配置 |
loading |
Object | {global: true, delay: 300, customLoading: null} |
加载配置 |
errorHandler |
Function | null |
全局错误处理器 |
validateStatus |
Function | (status) => status >= 200 && status < 300 |
状态码验证函数 |
性能与安全
XL-Request内置了多项性能和安全优化:
- 请求去重 - 避免短时间内发送相同请求
- 请求优先级 - 优先处理关键请求
- 自动超时处理 - 避免请求长时间挂起
- 错误重试 - 临时网络问题自动恢复
- 请求限流 - 控制并发请求数量
兼容性
XL-Request基于Fetch API和Promise实现,兼容以下平台:
- H5
- 微信小程序
- App (iOS/Android)
- 支付宝小程序
- 百度小程序
- 字节跳动小程序
许可证
MIT