uniapp封装uni.request请求

254 阅读1分钟

lang.js

// url常量文件
import urlConstants from '@/constants/urlConstants.js';

// 基础url
const BASE_URL = 'https://xxx';

const sendRequest = (params) => {
    let data = params.data || {};
    
    let header = {
        'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'
    }
    
    // 全局修改data
    if (uni.getStorageSync('token')) {
        data.token = uni.getStorageSync('token');
    }
    
    // 全局修改header
    if (params.json) {
        header = {
            'Content-Type': 'application/json'
        }
    }

    uni.showLoading({
        title: '数据加载中...'
    })

    uni.request({
        url: BASE_URL + params.url,
        data: data,
        method: params.method || 'POST',
        header: header,
        success: res => {
            params.success(res)
            if (0 === res.data.code) {
                uni.$showMsg(res.data.msg)
            } else if (401 === res.data.code) {
                // 登录过期
                uni.$showMsg(res.data.msg)
                uni.removeStorageSync('token')

                // #ifdef H5
                setTimeout(() => {
                    if (('/' + uni.$util.getCurrentRoute()).indexOf(urlConstants.LOGIN_PAGE) < 0)
                        // 跳转登录页面并携带目前参数,方便登录成功后返回页面
                        uni.$util.redirectTo(urlConstants.LOGIN_PAGE + '?back=/' + uni.$util.getCurrentRoute());
                }, 1000)
                // #endif
                // #ifdef MP-WEIXIN
                this.$refs.auth.getCode()
                // #endif
            } else {
                uni.hideLoading()
            }
        },
        fail: () => {
            uni.hideLoading()
        }
    });
}

export default {
    BASE_URL,
    sendRequest
}
// #ifdef H5
const app_type =  'h5';
const app_type_name = 'H5';
// #endif

// #ifdef MP-WEIXIN
const app_type = 'weapp';
const app_type_name = '微信小程序';
// #endif

// #ifdef MP-ALIPAY
const app_type = 'aliapp';
const app_type_name = '支付宝小程序';
// #endif

// #ifdef MP-BAIDU
const app_type = 'baiduapp';
const app_type_name = '百度小程序';
// #endif

// #ifdef MP-TOUTIAO
const app_type = 'MP-TOUTIAO';
const app_type_name = '头条小程序';
// #endif

// #ifdef MP-QQ
const app_type = 'MP-QQ';
const app_type_name = 'QQ小程序';
// #endif

// #ifdef APP-PLUS
const app_type = 'app';
const app_type_name = 'APP';
// #endif

sendRequest(params) {
    var method = params.data != undefined ? 'POST' : 'GET', // 请求方式
        url = Config.baseUrl + params.url, // 请求路径
        data = {
            app_type,
            app_type_name
        };
        
    // token
    if (uni.getStorageSync('token')) data.token = uni.getStorageSync('token');

    // 参数
    if (params.data != undefined) Object.assign(data, params.data);

    if (params.async === false) {
        //同步
        return new Promise((resolve, reject) => {
            uni.request({
                url: url,
                method: method,
                data: data,
                header: params.header || {
                    'content-type': 'application/x-www-form-urlencoded;application/json',
                    'token': uni.getStorageSync('token')
                },
                dataType: params.dataType || 'json',
                responseType: params.responseType || 'text',
                success: (res) => {
                    resolve(res.data);
                },
                fail: (res) => {
                    reject(res);
                },
                complete: (res) => {
                    reject(res);
                }
            });
        });
    } else {
        //异步
        uni.request({
            url: url,
            method: method,
            data: data,
            header: params.header || {
                'content-type': 'application/x-www-form-urlencoded;application/json',
                'token': uni.getStorageSync('token')
            },
            dataType: params.dataType || 'json',
            responseType: params.responseType || 'text',
            success: (res) => {
                // 登录过期
                if (401 === res.data.code && uni.getStorageSync('token')) {
                    uni.$showMsg(res.data.msg)
                    uni.removeStorageSync('token')
                    setTimeout(() => {
                        // 跳转登录页面
                    }, 1000)
                }
                typeof params.success == 'function' && params.success(res.data);
            },
            fail: (res) => {
                typeof params.fail == 'function' && params.fail(res);
            },
            complete: (res) => {
                typeof params.complete == 'function' && params.complete(res);
            }
        });
    }
}

// 同步调用
 async getData() {
    let res = await sendRequest({
        url: '/xxx',
        data: {},
        async: false
    })
    console.dir(res)
}