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
})
}
uniapp全局拦截封装(一)
sleeppingfrog2023-12-12 11:32
相关推荐
Dumbness13 小时前
订阅消息弹窗必须在用户点击里调:联调实验室里 timing 和 Mock 支付通知踩的坑码间留白2 天前
uni-app 鸿蒙离线打包:一个改动从源码到真机要穿过几条链多客:duokelijie2 天前
代练订单系统选型思路:跨品类游戏接入、订单分层管理、自动结算逻辑拆解!码间留白3 天前
鸿蒙端对接 BLE 血压计:从一次握手到读数入库(二)设备篇华玥作者4 天前
Vue 3 + TypeScript + uni-app 组件库推荐:hy-app(华玥组件库)FinelyYang4 天前
uniapp使用kkfileview在线预览ppt,excel,word,pdf类型文件2501_916008894 天前
iPhone 设备信息查看,用 KeyMob 看型号、序列号、电池健康和 UDIDModyQyW4 天前
vite-plugin-uni-manifest 0.7:在 uni-app 读取之前生成lyz2468594 天前
uniapp vue3 小程序开发注意事项雪芽蓝域zzs5 天前
WebStorm Uniapp Support + Uniapp Tool + Uniappx Language Service讲解