原生小程序使用 flyio,以及拦截器

2 篇文章 0 订阅
2 篇文章 0 订阅

原生小程序的request请求都是异步请求,在实际项目中使用起来很麻烦,自己封装的方法又不够用,所以想到了flyio,不仅可以实现Promise,而且还可以对所有的页面请求进行拦截,使用起来非常的方便。

第一件事首先也是先引用flyio.js了。

下载地址:flyio.js

在utils目录新建http.js


var Fly = require("flyio.js")//引入路径根据自己放置的目录配置
var fly = new Fly;
fly.interceptors.request.use((request) => {
    request.timeout = 30000;

    if (wx.getStorageSync('token')) {//检查本地缓存是否有token存在没有则重新获取
        request.headers = {//设置请求头
            "content-type": "application/json",
            "cld.stats.page_entry": wx.getStorageSync('scene'),
            "version": app.globalData.version,
            "token": wx.getStorageSync('token')
        }
        return request;
    } else {
        fly.lock();//锁住请求
        return app.Load().then(res => {//重新获取token
            request.timeout = 30000,
                request.headers = {//设置请求头
                    "content-type": "application/json",
                    "cld.stats.page_entry": wx.getStorageSync('scene'),
                    "version": app.globalData.version,
                "token": wx.getStorageSync('token')
                }
            wx.showLoading({
                title: "加载中",
                mask: true,
            });
            fly.unlock();//解锁请求
            return request;//继续之前的请求
        })
    }
})

fly.interceptors.response.use(
    (response) => {
        wx.hideLoading();
        return response;//请求成功之后将返回值返回
    },
    (err) => {
        //请求出错,根据返回状态码判断出错原因
        console.log(err)
        wx.hideLoading();
        if (err.status == 0) {
            return "网络连接异常"
        } else if (err.status == 1) {
            return "网络连接超时"
        } else if (err.status == 401) {
            return "用户未登录"
        } else {
            if (err.response.data.message) {
                return err.response.data.message
            } else {
                return '请求数据失败,请稍后再试'
            }
        };
        // Do something with response error
    }
)
export default {
    fly: fly
}

在其他页面引用

import http from "../../utils/http.js"

使用:

  http.fly.post(baseUrl + 'tt/news', {
            type: 1,
            page: 1
        }).then(res => {
            console.log(res)
        })

具体使用文档:https://wendux.github.io/dist/#/doc/flyio/readme

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 16
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 16
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值