美文网首页
uni-app中使用flyio

uni-app中使用flyio

作者: _undefined | 来源:发表于2019-11-06 10:12 被阅读0次

    Flyio帮助文档

    import Fly from 'flyio/dist/npm/wx';
    
    const fly = new Fly();
    
    // 请求拦截
    fly.interceptors.request.use(request => {
        let token = getApp().globalData.app.$store.state.token;
        if (token) {
            request.headers['Authorization'] = `bearer ${token}`;
        }
        return request;
    });
    
    // 响应拦截
    fly.interceptors.response.use(
        response => {
            return response.data;
        },
        err => {
            let errRes = undefined;
            switch (err.status) {
                case 0:
                    uni.showModal({
                        title: '请求超时',
                        content: '请稍后重试!',
                        showCancel: false
                    });
                    break;
                case 401:
                    uni.showModal({
                        title: '登陆失效',
                        content: '请从新登陆!',
                        showCancel: false
                    }).then(res => {
                        if (res[1].confirm) {
                            getApp().globalData.app.$store.commit('user/sync_loginData', {});
                            uni.reLaunch({
                                url: '/pages/login/index'
                            });
                        }
                    });
                    break;
                default:
                    errRes = err.response && err.response.data && err.response.data.errors;
                    if (errRes && errRes.length) {
                        uni.showModal({
                            title: 'Error',
                            content: `${errRes[0].message}`,
                            showCancel: false
                        });
                    }
                    console.log(err);
            }
        }
    );
    
    Reflect.getPrototypeOf(fly).fetch = options => {
        let opts = Object.assign(
            {
                url: '',
                method: 'POST',
                param: {},
                toast: {
                    loading: true
                }
            },
            options || {}
        );
    
        fly.config = {
            method: opts.method,
            baseURL: 'https://xxx.com',
            timeout: 0
        };
    
        if (opts.toast.loading) {
            uni.showLoading({
                mask: true,
                title: '正在加载'
            });
        }
    
        return fly.request(opts.url, opts.param).finally(() => {
            uni.hideLoading();
        });
    };
    
    export default fly;
    
    

    相关文章

      网友评论

          本文标题:uni-app中使用flyio

          本文链接:https://www.haomeiwen.com/subject/xznybctx.html