成都网站建设设计

将想法与焦点和您一起共享

记录转载:uni-app 请求 uni.request封装使用

这里给大家分享我在网上总结出来的一些知识,希望对大家有所帮助

我们提供的服务有:做网站、成都做网站、微信公众号开发、网站优化、网站认证、邯山ssl等。为成百上千企事业单位解决了网站和推广的问题。提供周到的售前咨询和贴心的售后服务,是有科学管理、有技术的邯山网站制作公司

对uni.request的一些共同参数进行简单的封装,减少重复性数据请求代码。方便全局调用。

先在目录下创建 utils 和 common 这2个文件夹

utils 是存放工具类的,common 用来放置常用方法的

之后在utils 中创建 requset.js 用来放置 uni.request 的请求方法,在对其进行简单的封装。

requset.js 代码

import operate from '../common/operate.js'
// vuex 的使用  详情参考官网 https://uniapp.dcloud.io/vue-vuex
import store from '../store/index.js'  

export default class Request {
    http(param) {
        // 请求参数
        var url = param.url,
            method = param.method,
            header = {},
            data = param.data || {},
            token = param.token || "",
            hideLoading = param.hideLoading || false;

        //拼接完整请求地址
        var requestUrl = operate.api + url;
       //拼接完整请求地址(根据环境切换)
       // var requestUrl = operate.api() + url;

        //请求方式:GET或POST(POST需配置
        // header: {'content-type' : "application/x-www-form-urlencoded"},)
        if (method) {
            method = method.toUpperCase(); //小写改为大写
            if (method == "POST") {
                header = {
                    'content-type': "application/x-www-form-urlencoded"
                };
            } else {
                header = {
                    'content-type': "application/json"
                };
            }
        }

        //加载圈
        if (!hideLoading) {
            uni.showLoading({
                title: '加载中...'
            });
        }

        // 返回promise
        return new Promise((resolve, reject) => {
            // 请求
            uni.request({
                url: requestUrl,
                data: data,
                method: method,
                header: header,
                success: (res) => {
                    // 判断 请求api 格式是否正确
                    if (res.statusCode && res.statusCode != 200) {
                        uni.showToast({
                            title: "api错误" + res.errMsg,
                            icon: 'none'
                        });
                        return;
                    }
                    // 将结果抛出
                    resolve(res.data)
                },
                //请求失败
                fail: (e) => {
                    uni.showToast({
                        title: "" + e.data.msg,
                        icon: 'none'
                    });
                    resolve(e.data);
                },
                //请求完成
                complete() {
                    //隐藏加载
                    if (!hideLoading) {
                        uni.hideLoading();
                    }
                    resolve();
                    return;
                }
            })
        })
    }
}

分享题目:记录转载:uni-app 请求 uni.request封装使用
文章分享:http://chengdu.cdxwcx.cn/article/dsojpso.html