uni-app响应拦截和请求函数合二为一的封装

请求参数和uni-app的文档要求的一模一样

注意参数不要传success和fail函数!!否则会不支持promise

/**
 * 请求函数和响应拦截
 * @param { object } options 和文档要求的参数一样
 * @returns { object | null }
 */
export const http = async (options) => {
  try {
    const res = await uni.request({ ...options })
    // axios就是这么判断的
    if (res.statusCode >= 200 && res.statusCode < 300) {
      console.log('请求成功')
      return res
    } else if (res.statusCode === 401) {
      // 清除token
      console.log('登陆状态过期,请重新登陆')
      return null
    } else {
      uni.showToast({
        icon: 'none',
        title: res.data?.msg || '请求错误',
      })
      return null
    }    
  } catch (err) {
    uni.showToast({
      icon: 'none',
      title: '网络错误,换个网络试试',
    })
    console.log(err)
    return null
  }
}

用法:

import { http } from '路径'

const getDtail = async () => {
  const res = await http({
      url: '',
      method: 'GET'
   })

   console.log(res)
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值