微信小程序request请求的二次封装、uni-app、Taro.request

欢迎点击领取 -《前端开发面试题进阶秘籍》:前端登顶之巅-最全面的前端知识点梳理总结

*分享一个使用比较久的🪜

1、简介

自带的微信小程序请求及框架类请求,书写比较繁琐;为了简写方便和全局处理封装的请求,因此我们对Taro.request请求二次封装和uni.request请求二次封装;以及包含常用的工具库封装,包含路由的跳转方法等

1.1 Taro.request
import Taro from '@tarojs/taro'
import api from "../api/login";

const BASE_URL = 'https://www.123fe.net'

/**
 * @param {Object} props
 * @description 针对搜索值做统一处理
 */
const convertParams = (props) => {
  const newParams = {};
  for (const index in props) {
    const item = props[index];
    const type = typeof item;
    if (item || item === false || item === 0) {
      if (item && type === 'string') {
        newParams[index] = item.replace(/\s/g, '');
      }
      if (Object.prototype.toString.call(item) === '[object Object]') {
        newParams[index] = convertParams(item)
      } else {
        newParams[index] = item;
      }
    }
  }
  return newParams;
};

interface configData {
  contentType?: string
}

const codeMessage = {
  200: '服务器成功返回请求的数据。',
  201: '新建或修改数据成功。',
  202: '一个请求已经进入后台排队(异步任务)。',
  204: '删除数据成功。',
  400: '发出的请求有错误。',
  401: '用户没有权限(令牌、用户名、密码错误)。',
  403: '用户得到授权,但是访问是被禁止的。',
  404: '请求资源不存在。',
  406: '请求的格式不可得。',
  410: '请求的资源被永久删除,且不会再得到的。',
  422: '当创建一个对象时,发生一个验证错误。',
  500: '服务器发生错误,请检查服务器。',
  502: '网关错误。',
  503: '服务不可用,服务器暂时过载或维护。',
  504: '网关超时。',
};

const baseOptions = (url: string, params: object = {}, method = 'get', config: configData = {}) => {
  const { contentType } = config
  Taro.showLoading({ title: "", mask: false });
  const option: any = {
    url: BASE_URL + url,
    data: params,
    method: method,
    timeout: 10000,
    header: { 'content-type': contentType || 'application/json;charset=UTF-8', Authorization: Taro.getStorageSync('token') },
    success(response) {
      Taro.hideLoading();
      const data = response.data;
      if (data.code === 200) return data
      if (data.code === 403) return removeSorage()
      Taro.showToast({
        icon: 'none',
        duration: 3000,
        title: data.msg || '',
      })
      return data
    },
    error(err) {
      Taro.hideLoading();
      if (err.statusCode === 403) return removeSorage()
      Taro.showToast({
        icon: 'none',
        duration: 3000,
        title: codeMessage[err.statusCode] || '',
      })
      return Promise.reject(err)
    }
  }
  return Taro.request(option)
}


const request = async (url: string, params: object = {}, method = 'get', config?) => {
  params = convertParams(params)
  try {
    const res = await baseOptions(url, params, method, config)
    return res.data
  } catch (err) {
    throw new Error(err)
  }
}

// 获取当前用户个人信息
const getUserInfo = async () => {
  const res = await api.userinfo();
  if (res.code !== 200) return false;
  const data = res.data
  if (!data.vipType) {
    Taro.setStorageSync("vipTypeOpen", true);
  }
  Taro.setStorageSync("userInfo", data);
  return true
};

const removeSorage = () => {
  Taro.removeStorage({ key: 'userInfo' })
  Taro.removeStorage({ key: 'token' })
  location.reload()
}

export { request, getUserInfo, removeSorage }

1.2 uni.request
interface requestInt {
  url: string,
  method: 'GET' | 'POST' | 'DELETE' | 'PUT',
  params: string | object | ArrayBuffer,
  options?: any,
}

/**
 * @param {Object} props
 * @description 针对搜索值做统一处理
 */
const convertParams = (props) => {
  const newParams = {};
  for (const index in props) {
    const item = props[index];
    const type = typeof item;
    if (item || item === false || item === 0) {
      if (item && type === 'string') {
        newParams[index] = item.replace(/\s/g, '');
      }
      if (Object.prototype.toString.call(item) === '[object Object]') {
        newParams[index] = convertParams(item)
      } else {
        newParams[index] = item;
      }
    }
  }
  return newParams;
};

const codeMessage = {
  200: '服务器成功返回请求的数据。',
  201: '新建或修改数据成功。',
  202: '一个请求已经进入后台排队(异步任务)。',
  204: '删除数据成功。',
  400: '发出的请求有错误。',
  401: '用户没有权限(令牌、用户名、密码错误)。',
  403: '用户得到授权,但是访问是被禁止的。',
  404: '请求资源不存在。',
  406: '请求的格式不可得。',
  410: '请求的资源被永久删除,且不会再得到的。',
  422: '当创建一个对象时,发生一个验证错误。',
  500: '服务器发生错误,请检查服务器。',
  502: '网关错误。',
  503: '服务不可用,服务器暂时过载或维护。',
  504: '网关超时。',
};

const request = (baseOptions: requestInt) => {
  const { url, method, params, options } = baseOptions
  const { contentType } = options || {}
  uni.showLoading({ title: '加载中...', mask: true });
  return new Promise<any>((resolve, reject) => {
    uni.request({
      url: `${import.meta.env.VITE_BASE_API}${url}`,
      method,
      data: convertParams(params),
      header: {
        'content-type': contentType || 'application/json;charset=UTF-8',
        Authorization: 'Bearer ' + uni.getStorageSync('token')
      },
      success: (res: any) => {
        uni.hideLoading();
        switch (res.statusCode) {
          case 200:
            resolve(res.data)
            break;
          default:
            uni.showModal({
              title: '温馨提示',
              content: '未知异常,请稍后在试!',
              showCancel: false,

            });
            reject(res)
        }
      },
      fail: (err: any) => {
        uni.hideLoading();
        uni.showToast({
          icon: 'none',
          duration: 3000,
          title: codeMessage[err.statusCode] || '',
        })
        reject(err)
      }
    })
  })
}

export default request
1.3 以上方法的使用案例:
// 创建的api.js文件
import { request } from '../utils/service';
const api = {
	login: () => '/api/login'
}

const userLogin = (params = {}) => request(api.login(), params, 'post')

export default { userLogin }
2. 常用的工具类方法(路由跳转)

uni-app同类型做下引用的替换,这里就不重复写了;

import Taro from '@tarojs/taro'

// 打开新页面并跳转
function navigateTo(url, params?) {
  const paramsStr = handleParams(params)
  Taro.navigateTo({
    url: url + paramsStr
  })
}

// 关闭当前页面并跳转新的页面
function redirectTo(url, params?) {
  const paramsStr = handleParams(params)
  Taro.redirectTo({
    url: url + paramsStr
  })
}

// 返回上级页面
function navBack(delta) {
  let currentDelta = delta
  if (!delta || typeof delta !== 'number') {
    currentDelta = 1
  }
  Taro.navigateBack({ delta: currentDelta }).then(r => r)
}

// 关闭所有页面并跳转到tabBar页面
function switchTab(url) {
  Taro.switchTab({
    url: url
  }).then(r => r)
}

// 参数转换拼接
function handleParams(params) {
  let paramsStr = ''
  if (params && typeof params === 'object') {
    const keys = Object.keys(params) || []
    if (keys && keys.length) {
      keys.forEach((key, index) => {
        if (index === 0) {
          paramsStr += `?${key}=${params[key]}`
        } else {
          paramsStr += `&${key}=${params[key]}`
        }
      })
    }
  }
  return paramsStr
}

export {
  navigateTo,
  redirectTo,
  navBack,
  switchTab,
  handleParams,
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

SunnyRun!

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值