下载该项目,解压移动文件夹dist里wxApiInterceptors.js和runtime.js文件到你自己的项目,详见示例。
const wxApiInterceptors = require('./wxApiInterceptors');wxApiInterceptors(); // 必须在调用小程序api之前调用小程序api调用不必传success、complete和fail参数。
⚠️注意:原生小程序项目不支持Promise.finally函数式异步调用方式: wx.showLoading({title: '登录中...'}) .then(wx.login) .then(data => wx.request.post('/login', {data})) .then(() => wx.showToast({title: '登录成功'})) .catch(() => wx.showToast({title: '登录失败'})) .finally(wx.hideLoading);也兼容原生的调用方式(不便维护): wx.showLoading({ title: '登录中...', success: () => { wx.login({ success: (data) => { wx.request({ url: '/login', data, success: () => wx.showToast({title: '登录成功'}), fail: () => wx.showToast({title: '登录失败'}), complete: wx.hideLoading, }); }, }); },});自定义拦截器使用方法及参数:wxApiInterceptors({[api]: {[request](params):params, [response](res):res}})
比如拦截wx.showModal的confirmColor默认值为red,调用成功后并拦截调用成功返回的结果。 wxApiInterceptors({ showModal: { request(params) { if (params.confirmColor === undefined) { params.confirmColor = 'red'; } return params; }, response(res) { res = '调用成功'; return res; }, }});wx.showModal({title: '测试'}) .then(console.log);// 控制的输出:调用成功默认拦截了request api,封装成了和axios差不多的使用方式调用wx.request[method](url, [config])发送axios化的请求。
默认GET请求 wx.request('https://test.com/banner') .then(({data}) => { console.log(data); })其他请求方式 wx.request.post('https://test.com', {data: {userName: 'test'}}) .then(({data}) => { console.log(data); })当然也可以再继续拦截request api比如设置request api默认的host:
wxApiInterceptors({ request: { request(params) { const host = 'https://test.com' if (!/^(http|//)/.test(params.url)) { params.url = host + params.url; } return params; }, },});甚至可以拦截自己的业务状态码:
wxApiInterceptors({ request: { response(res) { const {data: {code}} = res; // 如果data里的code等于-1就响应为失败 if (code === -1) { return Promise.reject(res); } return res; }, },});强大的async拦截器比如调用request api的时候都在header里带上本地储存的token,没有的话从服务器获取:
wxApiInterceptors({ request: { async request(params) { if (params.header === undefined) { params.header = {}; } let token = wx.getStorageSync('token'); if (!token) { ({data: token} = await wx.request('/getToken')); wx.setStorageSync('token', token); } params.header.token = token; return params; }, },});原生小程序项目使用async需要特殊处理,请看示例。