• uni-app 封装api请求


    1,封装API请求步骤

    uni-app中封装API请求可以按照以下步骤进行:

    1. 创建一个utils文件夹,并在其中创建一个api.js文件,用于存放API请求相关的代码。

    2. 在api.js文件中,引入uni.request方法用于发送请求。示例代码如下:

    export function request(url, method, data) {
      return new Promise((resolve, reject) => {
        uni.request({
          url: url,
          method: method,
          data: data,
          success: (res) => {
            resolve(res.data);
          },
          fail: (err) => {
            reject(err);
          }
        });
      });
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15

    这里使用了Promise对象来处理异步请求,方便后续的使用和处理。

    1. 在api.js文件中,定义具体的API请求函数。示例代码如下:
    import { request } from './utils/api';
    
    export function login(username, password) {
      const url = 'https://api.example.com/login';
      const method = 'POST';
      const data = {
        username: username,
        password: password
      };
      return request(url, method, data);
    }
    
    export function getUserInfo(userId) {
      const url = `https://api.example.com/users/${userId}`;
      const method = 'GET';
      return request(url, method);
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17

    以上示例代码中包括了登录和获取用户信息两个API请求函数。根据具体的需求,你可以进行修改或添加其他的API请求函数。

    1. 在需要使用API的页面或组件中引入并调用定义的API请求函数即可。示例代码如下:
    import { login, getUserInfo } from './utils/api';
    
    login('example', 'password').then((res) => {
      console.log('登录成功', res);
    }).catch((err) => {
      console.error('登录失败', err);
    });
    
    getUserInfo(123).then((res) => {
      console.log('获取用户信息成功', res);
    }).catch((err) => {
      console.error('获取用户信息失败', err);
    });
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13

    以上示例代码展示了如何使用封装的API请求函数来进行登录和获取用户信息的操作。根据具体需求,你可以在相应的页面或组件中调用相关API请求函数。

    通过以上步骤,你就可以在uni-app中封装API请求,使代码结构更加清晰和可维护。记得根据实际情况进行适当的错误处理和数据处理。

    2,uni-app封装api请求改进

    // @/utils/request.js
    // #ifdef MP-WEIXIN
    const baseURL = "https://www.bradenhan.tech"
    // #endif 
    // #ifdef H5
    const baseURL = ""
    // #endif
    
    const timeout = 5000
    
    // 封装api请求
    const request = function(option){ 
        // 获取用户传入的url
        var url = baseURL + option.url; 
         
        // 添加提请求头
        var  header = option.header||{}
        if(!!option.needToken){
            // 添加token 
            header.Authorization =  'Bearer ' +  uni.getStorageSync('token');  
        }
        header.source=1;
        header.channel="h5";
        
        // 加载提示
        var loading = option.loading;
        // 如果有loading就显示loading
        if(loading){
            uni.showLoading(loading)
        }
      
      // 返回一个promise
        return new Promise((resolve,reject)=>{  
            // 发起一个request请求
            uni.request({
                url, //请求url
                method:option.method||"GET", //请求方法
                header, //请求头
                timeout,
                data:option.data||option.params, //请求数据
                success(res){
                    // 成功返回结果
                    if(res.statusCode===200){
                        resolve(res.data)
                        // 如果是101 没有权限
                        if(res.data.code==101){
                            uni.showToast({
                                title: res.data.msg,
                                icon:'none'
                            })
                            uni.redirectTo({
                                url: '/pages/login/index',
                            })
                        }
                        if(res.data.code!=200&&res.data.code!=0){
                            uni.showToast({
                                icon:'none',
                                title:res.data.msg||'请求错误'
                            })
                        }
                    } 
                },
                fail(err){
                    // 失败返回失败结果
                    uni.showToast({
                        title: '请求失败',
                        icon:'error'
                    })
                    console.error(err);
                    reject(err)
                },
                complete(){
                    // 完成 关闭loading
                    if(loading){
                        uni.hideLoading()
                    }
                }
            })
        })
    }
    
    // 定义get简洁方法
    request.get=function(url,config){
        return  request({
            url,
            method:"GET",
            ...config
        })
    }
    
    // 定义post简洁方法
    request.post=function(url,data,config){
        return  request({
            url,
            method:"POST",  
            ...config,
            data
        })
    }
    // 导出请求
    export default request;
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92
    • 93
    • 94
    • 95
    • 96
    • 97
    • 98
    • 99
    • 100
    • 101

    统一控制api.js

    request.post(url,data,needToken)
    
    • 1

    参数:

    • url 请求url

    • data 请求参数data

    • needToken 是否需要参数

    // @/api/index.js
    
    import request from '@/utils/request.js' 
    
    // 用户注册
    export function customUseRegister(data){
        return request.post("/xxxx1",data)
    }
    
    // 微信用户登录
    export function customUserLogin(data){
        return request.post("/xxxx2",data)
    } 
    
    // 更新用户信息 -- 需要使用Token
    export function customUserUpdate(data){
        return request.post("/xxxx3",data,{needToken: true})
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18

    组件中使用

    import { customUserLogin, customUseRegister,customUserUpdate } from '@/api/index.js'
    
    customUserUpdate(data).then((res) => {
      console.log('成功', res);  
    }).catch((err) => { 
      console.error('登录失败', err);
    });
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
  • 相关阅读:
    异常exception和错误error即推荐用法@sneakythrow
    02-MySQL库和表的操作
    TDH社区版上新宽表数据库Hyperbase,轻松实现海量数据的毫秒级精确检索
    redis的原理和源码-缓存的三个常见问题(缓存穿透、缓存击穿、缓存雪崩)
    with 语句包含递归 sql 改写
    IOU GIOU DIOU CIOU
    【论文笔记】图神经网络采样相关工作整理9.19
    CVTE C/C++研发实习面试(凉)
    Dubbo中@EnableDubbo注解原理
    java+jsp+servlet+sqlserver图书查询系统
  • 原文地址:https://blog.csdn.net/weixin_43025151/article/details/132739550