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
相关推荐
xiangxiongfly9152 天前
uni-app 组件总结2501_915918412 天前
iOS性能数据监控:从概念到工具实践,让应用运行更流畅2501_915909062 天前
全面解析前端开发中常用的浏览器调试工具及其使用场景wuxianda10302 天前
uniapp项目上架苹果商店4.3a被拒,3天极速解决方案2026.5.8小盼江3 天前
Uniapp小程序鲜花商城推荐系统 买家卖家双端(web+uniapp)fakaifa3 天前
【最新版】CRMEB Pro版v4.0系统源码 全开源+uniapp/PC前端+搭建教程小徐_23333 天前
Wot UI v1 升级 v2?这份迁移指南帮你少踩坑!游戏开发爱好者84 天前
使用Fiddler设置HTTPS抓包诊断Power Query网络问题棋宣4 天前
uni-app编译到微信小程序中,父传子props首次传递数据不接收的bug阳光先做5 天前
uniapp打包鸿蒙安装包问题