美文网首页
uniapp网络请求二次封装

uniapp网络请求二次封装

作者: 硅谷干货 | 来源:发表于2022-05-16 23:51 被阅读0次

    前言

    得益于插件和工具生态构建,uniapp已然成为当下最流行小程序框架,没有之一,每次搭建新项目使用api网络封装是必备的,为了不重复造轮子,以此笔记,这里我使用最原始的uni官网提供的 uni.request() 来进行二次封装,不再使用axios、luch-request等三方库进行封装。

    参考:uniapp官网api

    vue2版本

    const BASE_URL = 'https://tke.91zbk.com'; //域名抽取
    const HEADER = {
        'content-type': 'application/x-www-form-urlencoded'
    }; //头部
    
    const request = options => {
        let headerObj = HEADER;
        const token = uni.getStorageSync('accessToken');
        if (token) {
            headerObj = {
                'token': token,
                ...HEADER
            }
        }
        return new Promise((resolve, reject) => {
            uni.request({
                url: BASE_URL + options.url,
                method: options.method || 'GET',
                header: headerObj,
                data: options.data || {},
                dataType: 'json',
                success: res => {
                    console.log('res-->:', res)
                    // 有其他用户登录
                    if (res.data.code == 10001) {
                        uni.clearStorageSync('accessToken');
                        uni.navigateTo({
                            url: '/pages/login/index'
                        })
                    }
                    if (res.data.code !== 1) {
                        return uni.showToast({
                            title: res.data.msg,
                            icon: 'error'
                        });
                    }
                    resolve(res);
                },
                fail: err => {
                    reject(err);
                },
                catch: (e) => {
                    console.log(e);
                }
            });
        });
    };
    
    
    export const requestGet = (url, data) => {
        return request({
            method: 'GET',
            url,
            data
        })
    }
    
    export const requestPost = (url, data) => {
        return request({
            method: 'POST',
            url,
            data
        })
    }
    

    vue3版本

    import { BASE_URL } from "@/config"
    
    const HEADER = {
        'content-type': 'application/x-www-form-urlencoded'
    }; //头部
    
    class Request {
        // get请求
        public async get(url, data) {
            return this.request({
                method: 'GET',
                url,
                data
            });
        }
    
        // post请求
        public async post(url, data) {
            return this.request({
                method: 'POST',
                url,
                data
            });
        }
        
        // 上传文件
        public async uploadFile(url: string, file: string) {
            return new Promise((resolve, reject) => {
                uni.uploadFile({
                    url: BASE_URL + url, 
                    filePath: file,
                    name: 'file',
                    success: (uploadFileRes) => {
                        if(uploadFileRes.statusCode === 200) {
                            resolve(JSON.parse(uploadFileRes.data));
                        } else {
                            reject(uploadFileRes)
                        }
                    },
                    fail: (err) => {
                        reject(err)
                    }
                })
            })
        }
    
        private async request(options) {
            let headerObj = HEADER;
            const token = uni.getStorageSync('accessToken');
            // console.log(token);
            if (token) {
                headerObj = {
                    token: token,
                    ...HEADER
                };
            }
            return new Promise((resolve, reject) => {
                uni.request({
                    url: BASE_URL + options.url,
                    method: options.method || 'GET',
                    header: headerObj,
                    data: options.data || {},
                    dataType: 'json',
                    success: res => {
                        if (res.data.code !== 1) {
                            return uni.showToast({
                                title: res.data.msg
                            });
                        }
                        resolve(res);
                    },
                    fail: err => {
                        reject(err);
                    },
                    catch: e => {
                        console.log(e);
                    }
                });
            });
        }
    }
    
    export const request = new Request();
    
    

    uni 请求权限封装

    // 获取登录请求
    const doRequestLoginInfo = () => {
        // 发起授权登录
        uni.login({
            provider: 'weixin',
            onlyAuthorize: true,
            success: async loginRes => {
                const code = loginRes.code;
                formData.code = loginRes.code;
                // 拿code换取openid,接口获取
                if (code) {
                    const openRes = await wxloginGetopenid({ code });
                    const data = openRes.data.data;
                    formData.openid = data.openid;
                    formData.session_key = data.session_key;
                    // 获取昵称头像信息
                    doRequestUserProfile();
                }
            },
            fail: err => {
                // err.code是错误码
                console.log('err', err.code);
            }
        });
    };
    
    // 从相册选择
    const chooseIamgeFromAlbum = () => {
        return new Promise(resolve => {
            uni.authorize({
                scope: 'scope.camera',
                success() {
                    uni.chooseImage({
                        count: 1, 
                        sourceType: ['album'],
                        success: function(res) {
                            resolve(res.tempFilePaths[0]);
                        }
                    });
                }
            });
        });
    };
    
    // 拍照
    const chooseImageFromCamera = () => {
        return new Promise(resolve => {
            uni.authorize({
                scope: 'scope.camera',
                success() {
                    uni.chooseImage({
                        count: 1,
                        sourceType: ['camera'],
                        success: function(res) {
                            resolve(res.tempFilePaths[0]);
                        }
                    });
                }
            });
        });
    };
    
    // 获取登录信息(openid、nickname)
    const doRequestUserProfile = () => {
        uni.getUserProfile({
            desc: '获取头像昵称',
            success: res => {
                formData.avatar = res.userInfo.avatarUrl;
                formData.nickname = res.userInfo.nickName;
                //保存用户信息
                setAccountInfo(formData);
                doLogin();
            }
        });
    };
    
    // 获取经纬度
    const getLocation = (): Promise<any> => {
        return new Promise((resolve, reject) => {
            uni.getLocation({
                type: 'wgs84',
                success: res => {
                    resolve({
                        lat: res.latitude,
                        lng: res.longitude
                    });
                },
                fail: err => {
                    resolve(null);
                }
            });
        });
    };
    

    点赞加关注,永远不迷路

    相关文章

      网友评论

          本文标题:uniapp网络请求二次封装

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