vue项目中的接口封装

2021-07-14  本文已影响0人  熊啊熊c

通常在项目中以插件的形引入axios,或者在uniapp中使用官方提供的uni.request就可以很方便的在页面中发送请求,直接在页面内使用原生模块提供的方法,可能会产生以下缺点

因为在实际项目中涉及到请求地址很多且不同的场景比较少,所以暂时只对接口进行两次封装

目录

在src目录下新建api文件夹,新建request.js(通用请求) 文件 和module1.js(统一业务模块用到的请求) 文件

通用请求的封装

因为是通用请求,所以此处的代码思路就是,

// 更加通用的请求封装
export const commonRequest = (url: string, data: any,method:string='GET') => {
  var promise: any = new Promise((resolve: any, reject: any) => {
    const timestamp: any = new Date().getTime();
    const headerTrue: any = {
      "Content-Type": "application/json;charset=UTF-8",
      timestamp: timestamp,
    }
    uni.showLoading({
      title: "加载中…",
    });
    uni.request({
      header:headerTrue,
      url:'https://www.fastmock.site/mock/7b1c3934b8c86bd7f3412016350cfa22/lyt'+url,
      data,
      // @ts-ignore
      method,
      success:function (res:any){
        uni.hideLoading()
        if(res.data.code===0){
          resolve(res.data)
        }else{
          showError(res)
        }
      },
      fail: function(e: any) {
        uni.hideLoading();
        uni.showModal({
          content: `查询失败,错误信息为:${e.errMsg}`,
          showCancel: false,
        });
        console.log(e)
        reject("网络出错");
      },
      complete:()=>{
        uni.hideLoading();
      }
    })
  })
  return promise;
};


const showError = (res) => {
  console.log('错误处理了s'+res.data.code)
  // let that = this
  if (res) {
    /*console.log("------异常响应------", token)*/
    console.log("------异常响应------", res.data.code)
    console.log(typeof res.data.code)
    switch (res.data.code) {
      case 403:
        uni.showToast({
          title: '拒绝访问',
          icon: 'none',
          duration: 4000
        });
        break
      case 500:
        if (res.data.code === 100) {
          uni.showModal({
            title: '登录已过期',
            content: '很抱歉,登录已过期,请重新登录',
            confirmText: '重新登录',
            success: function (res) {
              if (res.confirm) {
                //去我的页面登录
                uni.navigateTo({
                  url: '/pages/login/login'
                });
              } else if (res.cancel) {
                console.log('用户点击取消');
              }
            }
          })
          // update-end- --- author:scott ------ date:20190225 ---- for:Token失效采用弹框模式,不直接跳转----
        }
        break
      case 404:
        uni.showToast({
          title: '很抱歉,资源未找到!',
          icon: 'none',
          duration: 4000
        });
        break
      case 504:
        uni.showToast({
          title: '网络超时',
          icon: 'none',
          duration: 2000
        });
        break
      case 502:
        uni.showToast({
          title: '服务器异常',
          icon: 'none',
          duration: 2000
        });
        break
      case 401:
        uni.showToast({
          title: '未授权,请重新登录',
          icon: 'none',
          duration: 4000
        });
        /*if (token == '') {
          setTimeout(() => {
            //去我的页面登录
            uni.switchTab({
              url: '/pages/views/mine'
            });
          }, 1500)
        }*/
        break
      default:
        uni.showToast({
          title: res.data.message,
          icon: 'none',
          duration: 4000
        });
        break
    }
  }
}

业务模块下的请求

此处就是给使用通用请求来发送特定的业务请求

import {commonRequest} from './requst'

export function List(type,pageNumber=1,pageSize=10){
  return commonRequest('/msgList',{
    pageSize,
    pageNumber
  })
}
上一篇 下一篇

猜你喜欢

热点阅读