@kinngyo/miniprogram-request
v0.0.5
Published
基于小程序二次封装request
Downloads
7
Readme
miniprogram-request
- miniprogram-request 支持微信、抖音多平台小程序请求封装
安装
npm i @kinngyo/miniprogram-request
# 或
npm add @kinngyo/miniprogram-request
基本使用
微信小程序
import MiniprogramRequest from '@kinngyo/miniprogram-request'
// 微信实例化
const wxRequest = new MiniprogramRequest<
{},
WechatMiniprogram.RequestOption,
WechatMiniprogram.RequestTask
>(wx.request, {
baseURL: 'https://example.com',
})
// 发送请求
wxRequest.request({ url: '/login' })
抖音小程序
import MiniprogramRequest from '@kinngyo/miniprogram-request'
// 抖音
const ttRequest = new MiniprogramRequest<{}, Parameters<typeof tt.request>[0]>(
tt.request,
{
baseURL: 'https://example.com',
},
)
// 发送请求
ttRequest.request({ url: '/login' })
添加节流
import MiniprogramRequest from '@kinngyo/miniprogram-request'
const wxRequest = new MiniprogramRequest(wx.request, {
baseURL: 'https://example.com',
throttle: new MiniprogramRequest.ThrottleController({ time: 1000 }),
})
// 发送请求
ttRequest.request({ url: '/login' })
高级用法
自定义参数
// 微信实例化
const wxRequest = new MiniprogramRequest<
{ format: boolean; toast: boolean },
WechatMiniprogram.RequestOption
>(wx.request, {
baseURL: 'https://example.com',
format: true, // 可在拦截器中用于返回格式化
toast: true, // 可在拦截器中用于弹窗提示
})
添加拦截器
import MiniprogramRequest, {
type RequestConfig,
} from '@kinngyo/miniprogram-request'
const wxRequest = new MiniprogramRequest(wx.request)
// 请求拦截器
const requestInterceptorManager = new MiniprogramRequest.InterceptorManager()
requestInterceptorManager.add<RequestConfig>({
fulfilled(config) {
return config
},
})
// 响应拦截器
const responseInterceptorManager = new MiniprogramRequest.InterceptorManager()
requestInterceptorManager.add<RequestConfig, RequestConfig>(() => {
return {
fulfilled(config) {
return config
},
rejected(config) {
return config
},
}
})
// 使用拦截器
wxRequest.use(requestInterceptorManager, responseInterceptorManager)
// 发送请求
wxRequest.request({ url: '/login' })
自定义节流
import MiniprogramRequest from '@kinngyo/miniprogram-request'
const throttle = MiniprogramRequest.ThrottleController({ time: 600 })
// 自定义回调
throttle.promise((resolve, reject) => { reject(new Error("频繁操作"))) })
// 使用节流
const wxRequest = new MiniprogramRequest(wx.request, { throttle })