@fubei/web-fetch
v1.0.1
Published
web请求
Downloads
49
Readme
@fubei/web-fetch 请求工具
@fubei/web-fetch是一个基于axios的强大HTTP请求工具,专为Web端设计,提供了统一的接口规范和丰富的功能增强。它具备请求签名、缓存机制、拦截器系统、并发控制、错误处理和请求取消等特性,让API调用更加简单、高效和安全。
安装
npm install @fubei/web-fetch --save基本用法
快速开始
import FsFetch from '@fubei/web-fetch'
// 创建实例
const fsFetch = new FsFetch({
appid: 'your-app-id',
salt: 'your-salt-key',
version: '1.0.0'
})
// 发起请求
fsFetch.request({
baseUrl: 'https://api.example.com',
url: '/user/info',
method: 'GET',
data: { userId: 123 }
})
.then(response => {
console.log('请求成功', response)
})
.catch(error => {
console.error('请求失败', error)
})常见请求示例
import FsFetch from '@fubei/web-fetch'
const fsFetch = new FsFetch()
// GET请求
fsFetch.request({
baseUrl: 'https://api.example.com',
url: '/users',
method: 'GET',
data: { page: 1, limit: 10 }
})
// POST请求(JSON格式)
fsFetch.request({
baseUrl: 'https://api.example.com',
url: '/users',
method: 'POST',
formatType: 'json',
data: { name: 'John', age: 30 }
})
// POST请求(表单格式)
fsFetch.request({
baseUrl: 'https://api.example.com',
url: '/users',
method: 'POST',
formatType: 'urlencoded',
data: { name: 'John', age: 30 }
})
// 使用缓存
fsFetch.request({
baseUrl: 'https://api.example.com',
url: '/data',
method: 'GET',
useCache: true // 启用缓存
})
// Mock请求
fsFetch.setMockUrl('https://mock.example.com')
fsFetch.request({
baseUrl: 'https://api.example.com',
url: '/users',
isMock: true // 使用Mock地址
})依赖版本
- axios: ^0.21.1 (兼容 0.21.1 ~ 1.x)
- ts-md5: ^1.2.7
- qs: ^6.9.6
使用场景
Web端HTTP请求工具,基于axios封装,提供统一的接口规范和功能增强:
- 请求签名
- 缓存机制
- 拦截器系统
- 并发控制
- 错误处理
- 请求取消
签名参数 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 | | withCredentials | Boolean | 选填 | 是否携带cookie信息(1.x版本新增) | false | | responseType | String | 选填 | 响应数据类型(1.x版本新增) | json,可选值:arraybuffer, blob, document, json, text, stream |
设置全局参数
setSignParams - 设置加盐密钥
import FsFetch from '@fubei/web-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/web-fetch'
const fsFetch = new FsFetch()
fsFetch.setTimeout(12000)setDefaultHeader - 设置默认Content-Type
不设置,默认urlencoded;支持入参json,formdata,urlencoded
import FsFetch from '@fubei/web-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/web-fetch'
const fsFetch = new FsFetch()
fsFetch.setMockUrl('https://xxx')
// 需要在request传入isMock: true才会生效
// fsFetch.request({
// ...
// isMock: true
// ...
// })setInterceptor - 是否启用防重复请求
默认防重复点击开启,false 关闭
import FsFetch from '@fubei/web-fetch'
const fsFetch = new FsFetch()
fsFetch.setInterceptor(false)setRequerySite - 设置备用域名
支持单个域名或域名列表,[string | Array]
import FsFetch from '@fubei/web-fetch'
const fsFetch = new FsFetch()
fsFetch.requerySite('https://xxx')
// or
fsFetch.requerySite(['https://xxx1', 'https://xxx2'])setSwitchGateway - 是否允许切换域名
- 默认是允许切换域名的,如果设置了备用域名,当接口请求错误则自动切换为备用域名。
- 如果该设置设置为false, 则禁用切换域名
import FsFetch from '@fubei/web-fetch'
const fsFetch = new FsFetch()
fsFetch.setSwitchGateway(false)setDeleteKeyName - 校验参数需删除的参数名
默认删除signParams中的salt字段
import FsFetch from '@fubei/web-fetch'
const fsFetch = new FsFetch()
fsFetch.setDeleteKeyName('xxx')setCacheConfig - 设置缓存配置(1.x版本新增)
可以配置请求缓存,减少重复请求
import FsFetch from '@fubei/web-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/web-fetch'
import { IInterceptor } from '@fubei/web-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)setBaseConfig - 设置axios基础配置(1.x版本新增)
可以直接设置axios底层的一些基础配置
import FsFetch from '@fubei/web-fetch'
const fsFetch = new FsFetch()
fsFetch.setBaseConfig({
withCredentials: true, // 跨域请求是否携带cookie
maxRedirects: 5, // 最大重定向次数
maxContentLength: 2000, // 允许的最大响应内容大小
validateStatus: (status) => {
return status >= 200 && status < 300 // 自定义哪些HTTP状态码视为成功
}
})自定义处理方法
customHandleParams - 自定义请求参数处理方法
import FsFetch from '@fubei/web-fetch'
const fsFetch = new FsFetch()
/**
* 自定义请求参数处理方法
* @param data reqOptions.data
* @param signParams 加签
* @param reqOptions 请求的参数
*/
fsFetch.customHandleParams = (data, signParams, reqOptions) => {
// 自定义处理逻辑
return data
}customJudgeSuccess - 用户自定义成功判断函数
默认(result.success || result.code === '00000')判断为接口成功
import FsFetch from '@fubei/web-fetch'
const fsFetch = new FsFetch()
/**
* 自定义成功判断方法
* @param result httpResult
*/
fsFetch.customJudgeSuccess = (result) => {
// 自定义判断逻辑
return result.success || result.code === '00000'
}请求回调方法
customErrorHandle - 错误回调
可在此上传报错日志
import FsFetch from '@fubei/web-fetch'
const fsFetch = new FsFetch()
/**
* 错误回调
* @param error 返回的错误数据
* @param reqData 处理过请求的数据
* @param reqOptions 请求的参数
* @param context { baseUrl?: 当前请求的baseUrl, useTimes: 当前请求错误次数 } 当前请求的一些状态
*/
fsFetch.customErrorHandle = (error, reqData, reqOptions, { baseUrl, useTimes }) => {
// 错误处理逻辑
console.error('请求错误', error)
}customSuccessHandle - 成功回调
import FsFetch from '@fubei/web-fetch'
const fsFetch = new FsFetch()
/**
* 成功回调
* @param result 返回的成功数据
* @param reqData 处理过请求的数据
* @param reqOptions 请求的参数
* @param context { baseUrl?: 当前请求的url, useTimes: 当前请求错误次数 } 当前请求的一些状态
*/
fsFetch.customSuccessHandle = (result, reqData, reqOptions, { baseUrl, useTimes }) => {
// 成功处理逻辑
console.log('请求成功', result)
}customFinallyHandle - 请求结束回调
可以在这个里处理loading
import FsFetch from '@fubei/web-fetch'
const fsFetch = new FsFetch()
/**
* 请求完成回调
* @param result 返回的数据
* @param reqData 处理过请求的数据
* @param reqOptions 请求的参数
* @param context { url: 当前请求的url, useTimes: 当前请求错误次数 } 当前请求的一些状态
*/
fsFetch.customFinallyHandle = (result, reqData, reqOptions, { url, useTimes }) => {
// 关闭loading
if (reqOptions.loading) {
hideLoading() // 自定义关闭loading方法
}
}
// 需要在request传入loading
// fsFetch.request({
// ...
// loading: true
// ...
// })Web端特有功能(1.x版本新增)
文件上传(1.x版本新增)
在Web端上传文件到服务器
import FsFetch from '@fubei/web-fetch'
const fsFetch = new FsFetch()
// 单文件上传
const formData = new FormData()
formData.append('file', document.querySelector('input[type="file"]').files[0])
formData.append('user', 'test')
fsFetch.request({
baseUrl: 'https://api.example.com',
url: '/upload',
method: 'POST',
data: formData,
formatType: 'formdata', // 设置为formdata格式
onUploadProgress: (progressEvent) => {
const percentCompleted = Math.round((progressEvent.loaded * 100) / progressEvent.total)
console.log('上传进度', percentCompleted)
}
})
// 多文件上传
const multiFormData = new FormData()
const fileInput = document.querySelector('input[type="file"][multiple]')
for (let i = 0; i < fileInput.files.length; i++) {
multiFormData.append('files[]', fileInput.files[i])
}
fsFetch.request({
baseUrl: 'https://api.example.com',
url: '/upload/multiple',
method: 'POST',
data: multiFormData,
formatType: 'formdata'
})文件下载(1.x版本新增)
从服务器下载文件
import FsFetch from '@fubei/web-fetch'
const fsFetch = new FsFetch()
// 下载文件并获取二进制数据
fsFetch.request({
baseUrl: 'https://api.example.com',
url: '/download',
method: 'GET',
responseType: 'blob',
onDownloadProgress: (progressEvent) => {
const percentCompleted = Math.round((progressEvent.loaded * 100) / progressEvent.total)
console.log('下载进度', percentCompleted)
}
}).then(response => {
// 创建blob链接并触发下载
const url = window.URL.createObjectURL(new Blob([response.data]))
const link = document.createElement('a')
link.href = url
link.setAttribute('download', 'filename.ext') // 设置下载文件名
document.body.appendChild(link)
link.click()
link.remove()
window.URL.revokeObjectURL(url)
})跨域请求(1.x版本新增)
支持跨域请求和Cookie处理
import FsFetch from '@fubei/web-fetch'
const fsFetch = new FsFetch()
// 设置全局跨域携带凭证
fsFetch.setBaseConfig({
withCredentials: true
})
// 针对特定请求设置
fsFetch.request({
baseUrl: 'https://api.example.com',
url: '/cross-domain',
method: 'GET',
withCredentials: true // 允许跨域携带Cookie
})JSONP请求(1.x版本新增)
支持JSONP跨域请求
import FsFetch from '@fubei/web-fetch'
const fsFetch = new FsFetch()
fsFetch.jsonp('https://api.example.com/jsonp', {
callbackParamName: 'callback', // 指定回调参数名,默认为callback
timeout: 5000, // 超时时间
params: { // 额外参数
id: 123
}
}).then(data => {
console.log('JSONP响应数据', data)
})请求重试(1.x版本新增)
自动重试失败的请求
import FsFetch from '@fubei/web-fetch'
const fsFetch = new FsFetch()
fsFetch.request({
baseUrl: 'https://api.example.com',
url: '/data',
retryTimes: 3, // 最多重试3次
retryDelay: 1000, // 重试间隔1000ms
retryCondition: (error) => {
// 仅在网络错误或500错误时重试
return error.type === 'network' || (error.response && error.response.status >= 500)
}
})高级功能
取消请求(1.x版本新增)
可以通过取消令牌取消正在进行的请求
import FsFetch from '@fubei/web-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/web-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/web-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/web-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 from '@fubei/web-fetch'
import { IErrorResponse } from '@fubei/web-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, // 错误响应接口
IWebConfig // Web端特有配置接口
} from '@fubei/web-fetch'兼容性说明
版本兼容性
@fubei/web-fetch被设计为具有广泛的兼容性,支持不同版本的依赖库:
axios: 支持从0.21.1到最新版本的axios。
- 在0.21.1 ~ 0.27.x版本中,所有核心功能均可正常使用
- 在1.x版本中提供了一些性能优化和额外功能
- 对于特殊环境,可以使用0.21.1版本以获得最大兼容性
ts-md5: 1.2.7及以上版本都可以正常工作
- 不同版本的API保持一致性
qs: 6.9.7及以上版本都受支持
- 核心功能在各版本中保持稳定
浏览器兼容性
@fubei/web-fetch可以在以下环境中正常工作:
- 现代浏览器: Chrome, Firefox, Safari, Edge最新版本
- 较旧浏览器: 通过适当的polyfill和babel转换,可以支持IE11+
- 移动浏览器: 支持iOS Safari和Android Chrome
可能的兼容性问题
在某些情况下,您可能会遇到以下兼容性问题:
老旧环境下的Promise支持:如果在不支持Promise的环境中使用,请添加Promise polyfill。
低版本axios中的错误处理差异:低版本axios的错误结构可能略有不同,建议使用提供的错误处理增强方法。
不同版本间的TypeScript类型差异:如果使用TypeScript,请确保使用与@fubei/web-fetch兼容的类型定义。
如果遇到兼容性问题,可以通过以下方式解决:
// 为老旧环境添加Promise polyfill
import 'promise-polyfill/src/polyfill'
// 使用自定义错误处理以规避不同版本间的差异
import FsFetch from '@fubei/web-fetch'
const fsFetch = new FsFetch()
fsFetch.customErrorHandle = (error, reqData, reqOptions, { baseUrl, useTimes }) => {
// 错误处理逻辑
console.error('请求错误', error)
}