uniapp小程序request请求封装

  • Post author:
  • Post category:uniapp


一. 创建request文件夹–>创建index.js文件

第一种:

const config = require('./api.js'); // 请求的base URL

const getTokenHandle = () => {  
    return uni.getStorageSync('token')  // 获取登录用户token
}

// 请求白名单页面(不需要token请求的页面)
const pageWhiteList = ['pages/login/login', 'pages/login/phoneLogin'];

// 请求响应拦截处理
const resInterceptHandle = () => {
    const routes = getCurrentPages(); // 获取当前打开过的页面路由数组
    const curRoute = routes[routes.length - 1].route // 获取当前页面路由
    const flag = pageWhiteList.includes(curRoute)
    if (!flag) {
        console.log(`---[ ${curRoute} ]页面获取数据需要登录---`)
        uni.navigateTo({
            url: '/pages/login/login'
        })
    }
    return flag
}


// 请求参数处理
const requestParam = (data, method) => {
    let str = '';
    if (method == 'post') {
        str = JSON.stringify(data);
        return str;
    } else if (method == 'get') {
        for (let i in data) {
            str += i + '=' + data[i] + '&';
        }
        str = str.length > 0 ? str.substring(0, str.length - 1) : '';
        return encodeURI(str);
    }
};


// 请求封装
const sendRequest = (method = 'GET', url = '', params = {}, ) => {
    let promise = new Promise(async (resolve, reject) => {
        let token = await getTokenHandle()
        const URL = config.baseUcodeURL + url + (method === 'GET' ? params : '')
        //网络请求
        wx.request({
            header: {
                Authorization: token
            },
            url: URL,
            method,
            data: method === 'GET' ? {} : params,
            success: function(res) {
                // 响应403拦截跳转登录
                if (res.statusCode == 200 && res.data.status === 403) {
                    resInterceptHandle()
                    return
                }
                // 服务器返回数据
                if (res.statusCode == 200) {
                    resolve(res.data);
                } else {
                    console.log(`============${method} 请求失败:============`);
                    console.error(
                        '接口地址: ',
                        '【 ' + URL + ' 】'
                    );
                    console.error('请求参数: ', params);
                    console.error('返回结果: ', res);
                    wx.showToast({
                        title: res.data.emsg,
                        icon: 'none',
                        duration: 3000,
                        mask: true
                    });
                    reject(res);
                }
            },
            fail: function(res) {
                console.log(`============${method} 请求失败:============`);
                console.error(
                    '接口地址: ',
                    '【 ' + URL + ' 】'
                );
                console.error('请求参数: ', params);
                console.error('返回结果: ', res);
                reject(res);
            }
        });
    });
    return promise;
}


// 封装post请求(url:请求接口; data:请求参数;)
const httpPost = async (url, data) => {
    const params = requestParam(data, 'post');
    const res = await sendRequest('POST', url, params)
    console.log('post请求成功响应:', res)
    return res
};

// 封装get请求(url:请求接口; data:请求参数;)
const httpGet = async (url, data) => {
    let params = data && JSON.stringify(data) != '{}' ?
        '?' + requestParam(data, 'get') :
        '';
    const res = await sendRequest('GET', url, params)
    console.log('get请求成功响应', res)
    return res
};

// 自定义请求类型
const http = async (params = {
    method: 'GET',
    url: '',
    data: {}
}) => {
    const res = await sendRequest(params.method, params.url, params.data)
    console.log(`自定义${params.method}请求成功响应`, res)
    return res
};

module.exports = {
    Post: httpPost,
    Get: httpGet,
    http: http
};

第二种:

const config = require('./api.js'); // 请求的base URL

// 判断是否有token,没有跳转到登录页
const token = uni.getStorageSync("token");
   if (!token) {
       uni.navigateTo({
         url: "/pages/login/login",
       });
     resolve(false);
   } else {
     resolve(true);
   }


// 请求参数处理
const requestParam = (data, method) => {
    let str = '';
    if (method == 'post') {
        str = JSON.stringify(data);
        return str;
    } else if (method == 'get') {
        for (let i in data) {
            str += i + '=' + data[i] + '&';
        }
        str = str.length > 0 ? str.substring(0, str.length - 1) : '';
        return encodeURI(str);
    }
};


// 请求封装
const sendRequest = (method = 'GET', url = '', params = {}, ) => {
    let promise = new Promise(async (resolve, reject) => {
        let token = await getTokenHandle()
        const URL = config.baseUcodeURL + url + (method === 'GET' ? params : '')
        //网络请求
        wx.request({
            header: {
                Authorization: token
            },
            url: URL,
            method,
            data: method === 'GET' ? {} : params,
            success: function(res) {
                // 响应403拦截跳转登录
                if (res.statusCode == 200 && res.data.status === 403) {
                    resInterceptHandle()
                    return
                }
                // 服务器返回数据
                if (res.statusCode == 200) {
                    resolve(res.data);
                } else {
                    console.log(`============${method} 请求失败:============`);
                    console.error(
                        '接口地址: ',
                        '【 ' + URL + ' 】'
                    );
                    console.error('请求参数: ', params);
                    console.error('返回结果: ', res);
                    wx.showToast({
                        title: res.data.emsg,
                        icon: 'none',
                        duration: 3000,
                        mask: true
                    });
                    reject(res);
                }
            },
            fail: function(res) {
                console.log(`============${method} 请求失败:============`);
                console.error(
                    '接口地址: ',
                    '【 ' + URL + ' 】'
                );
                console.error('请求参数: ', params);
                console.error('返回结果: ', res);
                reject(res);
            }
        });
    });
    return promise;
}


// 封装post请求(url:请求接口; data:请求参数;)
const httpPost = async (url, data) => {
    const params = requestParam(data, 'post');
    const res = await sendRequest('POST', url, params)
    console.log('post请求成功响应:', res)
    return res
};

// 封装get请求(url:请求接口; data:请求参数;)
const httpGet = async (url, data) => {
    let params = data && JSON.stringify(data) != '{}' ?
        '?' + requestParam(data, 'get') :
        '';
    const res = await sendRequest('GET', url, params)
    console.log('get请求成功响应', res)
    return res
};

// 自定义请求类型
const http = async (params = {
    method: 'GET',
    url: '',
    data: {}
}) => {
    const res = await sendRequest(params.method, params.url, params.data)
    console.log(`自定义${params.method}请求成功响应`, res)
    return res
};

module.exports = {
    Post: httpPost,
    Get: httpGet,
    http: http
};

二. 在main.js中把封装的方法挂载到全局对象上

const {Get,http,Post} = require("./request/index");

Vue.prototype.$http = http
Vue.prototype.$get = Get
Vue.prototype.$post = Post

三. 使用

this.$post('/login/login', data).then(res => {}).catch(err=>{})



版权声明:本文为m0_58293192原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。