@fubei/mina-fetch
v1.0.1
Published
小程序请求
Readme
@fubei/mina-fetch 请求工具
安装
npm install @fubei/mina-fetch --save依赖版本
- ts-md5: ^1.2.7
- qs: ^6.9.6
签名参数 signParams
| 参数名称 | 类型 | 是否必填 | 描述 | 默认值 | | -------- | ------ | -------- | ------ | ------ | | appid | String | 选填 | 应用id | | | salt | String | 选填 | 盐 | | | version | String | 选填 | 版本号 | |
请求参数 reqOptions
| 参数名称 | 类型 | 是否必填 | 描述 | 默认值 | | ------------- | ------- | -------- | --------------- | ----------------- | | baseUrl | String | 必填 | 基本url | | baseUrlSuffix | String | 选填 | url 后缀,比如gateway默认空字符串 | | url | String | 必填 | 接口方法名 | | method | String | 选填 | 请求方式 | POST,可用值POST|GET|PUT|DELETE|PATCH|HEAD|OPTIONS | | timeout | Number | 选填 | 超时时间 | 不填默认使用全局的超时时间,10000 | | formatType | String | 选填 | 数据格式 | urlencode,可用值为json | formdata | urlencoded | | dataType | String | 选填 | dataType | json | | data | Object | 选填 | 请求数据 | | retryTimes | Number | 选填 | 请求次数 接口请求失败时自动重新请求 | 1 | | header | Object | 选填 | 请求头部 可在此设置请求头部请求格式、token | | sendRawData | Boolean | 选填 | 是否上传原始请求数据(为true时,常规请求接口,false,付呗方式请求接口) | false | | returnRawData | Boolean | 选填 | 不处理返回参数,否则返回res.data | false | | isMock | Boolean | 选填 | 是否mock | false | | switchGateway | Boolean | 选填 | 接口错误是否切换域名,设置了备用requerySite才会真正生效 | true | | cancelToken | Object | 选填 | 取消请求的令牌,可通过getCancelTokenSource()方法获取(1.x版本新增) | | | requestId | String | 选填 | 请求ID,可用于通过cancelRequest()方法取消请求(1.x版本新增) | | | useCache | Boolean | 选填 | 是否使用缓存,若设置为true,则当前请求将使用缓存机制(1.x版本新增) | false | | loading | Boolean | 选填 | 是否显示加载提示,可配合customFinallyHandle使用(1.x版本新增) | false | | priority | Number | 选填 | 请求优先级,用于请求队列中的排序,数字越小优先级越高(1.x版本新增) | 0 |
设置全局参数
setSignParams - 设置加盐密钥
import FsFetch from '@fubei/mina-fetch'
// 方式一
const fsFetch = new FsFetch({
appid:'xxxx',
salt:'xxxx',
version:'1.0.0'
})
// 方式二
const fsFetch = new FsFetch()
fsFetch.setSignParams({
appid:'xxxx',
salt:'xxxx',
version:'1.0.0'
})setTimeout - 设置超时时间
不设置,默认10000ms;改方法兼容旧版本 setAxiosTimeout 方法
import FsFetch from '@fubei/mina-fetch'
const fsFetch = new FsFetch()
fsFetch.setTimeout(12000)setDefaultHeader - 设置默认Content-Type 不设置,默认urlencoded;支持入参json,formdata,urlencoded
import FsFetch from '@fubei/mina-fetch'
const fsFetch = new FsFetch()
fsFetch.setDefaultHeader ('urlencoded')
// json: { 'Content-Type': 'application/json;charset=UTF-8' },
// formdata: { 'Content-Type': 'multipart/formdata;charset=UTF-8' },
// urlencoded: { 'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'setMockUrl - 设置mock地址
全局设置了mock地址后,需要设置request方法的isMock: true才会生效
import FsFetch from '@fubei/mina-fetch'
const fsFetch = new FsFetch()
fsFetch.setMockUrl ('https://xxx')
// 需要在request传入isMock: true才会生效
// fsFetch.request({
// ...
// isMock: true
// ...
// })setInterceptor - 是否启用防重复请求
默认防重复点击开启,false 关闭
import FsFetch from '@fubei/mina-fetch'
const fsFetch = new FsFetch()
fsFetch.setInterceptor (false)setRequerySite - 设置备用域名
支持单个域名或域名列表,[string | Array]
import FsFetch from '@fubei/mina-fetch'
const fsFetch = new FsFetch()
fsFetch.requerySite ('https://xxx')
// or
fsFetch.requerySite (['https://xxx1', 'https://xxx2'])setSwitchGateway - 是否允许切换域名
- 默认是允许切换域名的,如果设置了备用域名,当接口请求错误则自动切换为备用域名。
- 如果该设置设置为false, 则禁用切换域名
import FsFetch from '@fubei/mina-fetch'
const fsFetch = new FsFetch()
fsFetch.setSwitchGateway(false)setDeleteKeyName - 校验参数需删除的参数名
默认删除signParams中的salt字段
import FsFetch from '@fubei/mina-fetch'
const fsFetch = new FsFetch()
fsFetch.setDeleteKeyName('xxx')setCacheConfig - 设置缓存配置(1.x版本新增)
可以配置请求缓存,减少重复请求
import FsFetch from '@fubei/mina-fetch'
const fsFetch = new FsFetch()
// 设置缓存配置
fsFetch.setCacheConfig({
enable: true, // 是否启用缓存
maxAge: 60000, // 缓存有效期(毫秒),默认60000ms(1分钟)
capacity: 100 // 最大缓存条数,默认100条
})
// 清除所有缓存
fsFetch.clearCache()
// 清除特定请求的缓存(传入缓存键名)
fsFetch.clearCache('cacheKey')addInterceptor - 添加请求/响应拦截器(1.x版本新增)
拦截器可以在请求发送前和接收到响应后执行自定义逻辑
import FsFetch from '@fubei/mina-fetch'
import { IInterceptor } from '@fubei/mina-fetch'
const fsFetch = new FsFetch()
// 定义拦截器
const interceptor: IInterceptor = {
// 请求拦截器
request: (options, data) => {
console.log('请求即将发送', options, data)
// 可以修改options或data
return { options, data }
},
// 响应拦截器
response: (response) => {
console.log('收到响应', response)
// 可以修改response
return response
}
}
// 添加拦截器,返回拦截器ID,用于后续移除
const interceptorId = fsFetch.addInterceptor(interceptor)
// 移除特定拦截器
fsFetch.removeInterceptor(interceptorId)自定义处理方法
customHandleParams - 自定义请求参数处理方法
import FsFetch from '@fubei/mina-fetch'
const fsFetch = new FsFetch()
/**
* 自定义请求参数处理方法
* @param data reqOptions.data
* @param signParams 加签
* @param reqOptions 请求的参数
*/
fsFetch.customHandleParams = (data, signParams, reqOptions) => {
}customJudgeSuccess - 用户自定义成功判断函数
默认(result.success || result.code === '00000')判断为接口成功
import FsFetch from '@fubei/mina-fetch'
const fsFetch = new FsFetch()
/**
* 自定义请求参数处理方法
* @param result httpResult
*/
fsFetch.customJudgeSuccess = (result) => {
// return Boolean
}请求回调方法
customErrorHandle - 错误回调
可在此上传报错日志
import FsFetch from '@fubei/mina-fetch'
const fsFetch = new FsFetch()
/**
* 错误回调
* @param error 返回的错误数据
* @param reqData 处理过请求的数据
* @param reqOptions 请求的参数
* @param context { baseUrl?: 当前请求的baseUrl, useTimes: 当前请求错误次数 } 当前请求的一些状态
*/
fsFetch.customErrorHandle = (error, reqData, reqOptions, { baseUrl, useTimes }) => {
}customSuccessHandle - 成功回调
import FsFetch from '@fubei/mina-fetch'
const fsFetch = new FsFetch()
/**
* 成功回调
* @param error 返回的错误数据
* @param reqData 处理过请求的数据
* @param reqOptions 请求的参数
* @param context { baseUrl?: 当前请求的url, useTimes: 当前请求错误次数 } 当前请求的一些状态
*/
fsFetch.customErrorHandle = (result, reqData, reqOptions, { baseUrl, useTimes })=>{
}customFinallyHandle - 请求结束回调
可以在这个里处理loading
import FsFetch from '@fubei/mina-fetch'
const fsFetch = new FsFetch()
/**
* complate回调
* @param error 返回的错误数据
* @param reqData 处理过请求的数据
* @param reqOptions 请求的参数
* @param context { url: 当前请求的url, useTimes: 当前请求错误次数 } 当前请求的一些状态
*/
fsFetch.customFinallyHandle = (result, reqData, reqOptions, { url, useTimes }) => {
if (reqOptions.loading) {
wx.hideLoading()
}
}
// 需要在request传入loading
// fsFetch.request({
// ...
// loading: true
// ...
// })高级功能
取消请求(1.x版本新增)
可以通过取消令牌取消正在进行的请求
import FsFetch from '@fubei/mina-fetch'
const fsFetch = new FsFetch()
// 方式1:使用cancelToken
const source = fsFetch.getCancelTokenSource()
fsFetch.request({
baseUrl: 'https://api.example.com',
url: '/user/info',
cancelToken: source.token // 设置取消令牌
})
// 取消请求
source.cancel('请求被用户取消')
// 方式2:传入requestId,后续通过requestId取消请求
fsFetch.request({
baseUrl: 'https://api.example.com',
url: '/user/info',
requestId: 'user-info-request' // 设置请求ID
})
// 通过请求ID取消请求
fsFetch.cancelRequest('user-info-request')
// 检查请求是否被取消
const isCancel = fsFetch.isCancel(error) // 在catch块中判断错误是否是由取消引起的并发请求(1.x版本新增)
同时发送多个请求,等待所有请求完成
import FsFetch from '@fubei/mina-fetch'
const fsFetch = new FsFetch()
// 创建多个请求
const request1 = fsFetch.request({
baseUrl: 'https://api.example.com',
url: '/data1'
})
const request2 = fsFetch.request({
baseUrl: 'https://api.example.com',
url: '/data2'
})
// 使用all方法并发请求
fsFetch.all([request1, request2])
.then(fsFetch.spread((response1, response2) => {
// 处理response1和response2
console.log(response1, response2)
}))
.catch(error => {
// 任一请求失败都会进入catch
console.error(error)
})请求队列和请求限流(1.x版本新增)
适用于需要控制请求频率的场景
import FsFetch from '@fubei/mina-fetch'
const fsFetch = new FsFetch()
// 添加请求到队列,队列中的请求会被限制并发数
fsFetch.queue({
baseUrl: 'https://api.example.com',
url: '/data',
priority: 1 // 优先级,数字越小优先级越高
})
// 设置队列选项
fsFetch.setQueueOptions({
maxConcurrent: 2, // 最大并发数
retryTimes: 3, // 失败重试次数
retryDelay: 1000 // 重试间隔(毫秒)
})HTTP方法别名(1.x版本新增)
为常用HTTP方法提供简便的别名
import FsFetch from '@fubei/mina-fetch'
const fsFetch = new FsFetch()
// GET请求
fsFetch.get('https://api.example.com/users', {
params: { id: 1 }
})
// POST请求
fsFetch.post('https://api.example.com/users', {
name: 'John', age: 30
})
// 其他HTTP方法
fsFetch.delete('https://api.example.com/users/1')
fsFetch.put('https://api.example.com/users/1', { name: 'Updated' })
fsFetch.patch('https://api.example.com/users/1', { age: 31 })
fsFetch.head('https://api.example.com/users')
fsFetch.options('https://api.example.com/users')小程序特定功能
设置小程序平台(1.x版本新增)
设置当前使用的小程序平台类型
import FsFetch, { PlatformType } from '@fubei/mina-fetch'
const fsFetch = new FsFetch()
// 设置为微信小程序
fsFetch.setActivePlatform(PlatformType.WECHAT)
// 获取当前平台类型
const currentPlatform = fsFetch.getActivePlatform()可用的平台类型:
- PlatformType.WECHAT: 微信小程序
- PlatformType.ALIPAY: 支付宝小程序
- PlatformType.TOUTIAO: 抖音小程序
- PlatformType.DINGTALK: 钉钉小程序
- PlatformType.QQ: QQ小程序
- PlatformType.BAIDU: 百度小程序
- PlatformType.XIAOHONGSHU: 小红书小程序
文件上传(1.x版本新增)
上传文件到服务器
import FsFetch from '@fubei/mina-fetch'
const fsFetch = new FsFetch()
fsFetch.uploadFile({
baseUrl: 'https://api.example.com',
url: '/upload',
filePath: '/path/to/file', // 文件路径
name: 'file', // 文件对应的 key
header: { // 自定义请求头
'token': 'xxxx'
},
formData: { // 附加的表单数据
'user': 'test'
},
onProgressUpdate: (res) => {
console.log('上传进度', res.progress)
console.log('已上传数据长度', res.totalBytesSent)
console.log('预期需上传数据总长度', res.totalBytesExpectedToSend)
}
}).then(res => {
console.log('上传成功', res)
}).catch(err => {
console.error('上传失败', err)
})文件下载(1.x版本新增)
从服务器下载文件
import FsFetch from '@fubei/mina-fetch'
const fsFetch = new FsFetch()
fsFetch.downloadFile({
baseUrl: 'https://api.example.com',
url: '/download',
header: { // 自定义请求头
'token': 'xxxx'
},
onProgressUpdate: (res) => {
console.log('下载进度', res.progress)
console.log('已下载数据长度', res.totalBytesWritten)
console.log('预期需下载数据总长度', res.totalBytesExpectedToWrite)
}
}).then(res => {
console.log('下载成功', res)
console.log('临时文件路径', res.tempFilePath)
}).catch(err => {
console.error('下载失败', err)
})网络状态监听(1.x版本新增)
监听网络状态变化
import FsFetch from '@fubei/mina-fetch'
const fsFetch = new FsFetch()
// 监听网络状态
fsFetch.listenNetworkStatus((isConnected, networkType) => {
console.log('网络是否连接:', isConnected)
console.log('网络类型:', networkType) // wifi, 2g, 3g, 4g, 5g, unknown, none
})错误处理增强(1.x版本新增)
针对不同类型的错误提供更丰富的信息
import FsFetch from '@fubei/mina-fetch'
import { IErrorResponse } from '@fubei/mina-fetch'
const fsFetch = new FsFetch()
fsFetch.request({
baseUrl: 'https://api.example.com',
url: '/data'
}).then(res => {
// 成功处理
}).catch((error: IErrorResponse) => {
// 错误处理增强
console.log('错误状态码:', error.status)
console.log('错误信息:', error.message)
console.log('错误类型:', error.type) // network, timeout, cancel, server, unknown
console.log('请求参数:', error.request)
console.log('响应数据:', error.response)
// 特定错误类型判断
if (error.type === 'timeout') {
console.log('请求超时')
} else if (error.type === 'network') {
console.log('网络错误')
} else if (error.type === 'cancel') {
console.log('请求被取消')
}
})类型定义
使用TypeScript时导入以下类型可获得更好的代码提示和类型检查
import {
IReqOptions, // 请求选项接口
ISignParams, // 签名参数接口
IInterceptor, // 拦截器接口
ICacheConfig, // 缓存配置接口
IErrorResponse, // 错误响应接口
PlatformType // 小程序平台类型枚举
} from '@fubei/mina-fetch'