You signed in with another tab or window.
Reload
to refresh your session.
You signed out in another tab or window.
Reload
to refresh your session.
You switched accounts on another tab or window.
Reload
to refresh your session.
import wxApiInterceptors from 'wxapp-api-interceptors';
wxApiInterceptors(); // 必须在调用小程序api之前调用
下载
该项目,解压移动文件夹
dist
里
wxApiInterceptors.js
和
runtime.js
文件到你自己的项目,详见
示例
。
const wxApiInterceptors = require('./wxApiInterceptors');
wxApiInterceptors(); // 必须在调用小程序api之前调用
不必传success、complete和fail参数。
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}}, [isReturn]: boolean)
wxApiInterceptors({
showModal: {
request(params) {
if (params.confirmColor === undefined) {
params.confirmColor = 'red';
return params;
response(res) {
res = '调用成功';
return res;
});
wx.showModal({title: '测试'})
.then(console.log);
// 控制的输出:调用成功
调用
wx.request[method](url, [config])
发送axios化的请求。
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默认的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;
});
比如调用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需要特殊处理,请看示例。
小程序基础版本2.0.8后的小程序,在后台配置了插件不能直接调用全局wx对象issues,需要在调用wxApiInterceptors({}, true)时传入第二个参数为true,会返回一个代理后的对象以供调用,请看示例。