uniapp全局拦截封装(一)


const baseUrl="http://localhost:3000"

function showToast(msg, icon = 'error') {
  uni.showToast({
    title: msg,
    icon,
  });
}


// 添加拦截器
const httpInterceptor = {
  // 拦截前触发
  invoke(options) {
    // 1. 非 http 开头需拼接地址
    if (!options.url.startsWith('http')) {
      options.url = baseUrl + options.url;

      console.log("url--",options)
    }
    // 2. 请求超时, 默认 60s
    options.timeout = 60 * 1000;

    options.header={...options}
    // 3. 初始化header
     if (isBlank(options.header)) {
       options.header = {};
     }

    // 4. 添加 token 请求头标识
    const token =uni.getStorageSync("token")
 // 获取本地存储的token
    if (token) {
      options.header.Authorization = `Bearer ${token}`;
    }else{
       uni.redirectTo({
         url:"/pages/login/login"
       })
    }
    
  },
};

uni.addInterceptor('request', httpInterceptor);

export const http=(options)=> {
  return new Promise((resolve,reject)=>{
    if(options.loading) uni.showLoading({title: '加载中'});
    uni.request({
      ...options,
      success(res){
          // resolve(res)                
                  const rawData = res.data;
                  if (res.statusCode >= 200 && res.statusCode < 300) {
                    // 判断跟后端约定好的成功标识
                    if (rawData.code !== 0) {
                      showToast(rawData.message, 'none');
                    }
                    resolve(rawData);
                  } else if (res.statusCode === 401) {
                    // token 失效处理
                    reject(res);
                  } else {
                    switch (res.statusCode) {
                      case 404:
                        showToast('请求资源不存在');
                        break;
                      case 500:
                        showToast('服务器错误');
                        break;
                      case 502:
                        showToast('找不到对应服务器');
                        break;
                      default:
                        showToast(rawData?.message || '请求异常');
                        break;
                    }
                    reject(res);
                  }
      },
      complete(){
        if(options.loading) uni.hideLoading();
      },
      fail(err){
          reject(err)
      }
    })
  })
}


二:在api.jsw文件中
import {http} from "../utils/http"
import "../utils/http"

export const getList=()=>{
  return  http({
        method:"GET",
        url:"/api/list",
        loading:true
    })
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值