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
相关推荐
学会煎墙1 天前
使用uniapp——实现微信小程序的拖拽排序(vue3+ts)淡淡蓝蓝1 天前
uni-app小程序往飞书多维表格写入内容(包含图片)晨枫阳1 天前
uniapp兼容问题处理总结iOS阿玮1 天前
苹果 Swift 安卓SDK上线,用一套 Swift 代码开发安卓 App 成为可能!2501_915921431 天前
iOS混淆与IPA加固全流程(iOS混淆 IPA加固 Ipa Guard实战)liusheng1 天前
腾讯地图 SDK 接入到 uniapp 的多端解决方案游戏开发爱好者81 天前
iOS 26 App 开发阶段性能优化 从多工具协作到数据驱动的实战体系2501_915106321 天前
深入剖析 iOS 26 系统流畅度,多工具协同监控与性能优化实践游戏开发爱好者81 天前
iOS 26 App 查看电池寿命技巧,多工具组合实践指南xiaohe06011 天前
🚀 拥抱 create-uni,一行命令轻松集成 Uni ECharts!