微信小程序开发之api拦截器
白羽 2018-07-18 来源 :网络 阅读 5690 评论 0

摘要:本文将带你了解微信小程序开发之api拦截器,希望本文对大家学微信有所帮助。



微信小程序api拦截器完美兼容原生小程序项目完美兼用小程序api的原本调用方式,无痛迁移小程序api全Promise化和axios一样的请求方式小程序api自定义拦截调用参数和返回结果强大的async拦截快速开始安装npm install wxapp-api-interceptors --save使用mpvue等项目import wxApiInterceptors from 'wxapp-api-interceptors';

wxApiInterceptors(); // 必须在调用小程序api之前调用原生小程序项目下载该项目,解压移动文件夹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;
        },
    },
});

    

本文由职坐标整理并发布,希望对同学们有所帮助。了解更多详情请关注职坐标移动开发之微信频道!

本文由 @白羽 发布于职坐标。未经许可,禁止转载。
喜欢 | 6 不喜欢 | 5
看完这篇文章有何感觉?已经有11人表态,55%的人喜欢 快给朋友分享吧~
评论(0)
后参与评论

您输入的评论内容中包含违禁敏感词

我知道了

助您圆梦职场 匹配合适岗位
验证码手机号,获得海同独家IT培训资料
选择就业方向:
人工智能物联网
大数据开发/分析
人工智能Python
Java全栈开发
WEB前端+H5

请输入正确的手机号码

请输入正确的验证码

获取验证码

您今天的短信下发次数太多了,明天再试试吧!

提交

我们会在第一时间安排职业规划师联系您!

您也可以联系我们的职业规划师咨询:

小职老师的微信号:z_zhizuobiao
小职老师的微信号:z_zhizuobiao

版权所有 职坐标-一站式IT培训就业服务领导者 沪ICP备13042190号-4
上海海同信息科技有限公司 Copyright ©2015 www.zhizuobiao.com,All Rights Reserved.
 沪公网安备 31011502005948号    

©2015 www.zhizuobiao.com All Rights Reserved

208小时内训课程