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
相关推荐
q55070717711 小时前
uniapp/uniappx实现原生图片编辑涂鸦、贴图、滤镜、旋转、裁剪等计算机学姐1 天前
基于微信小程序的校园失物招领管理系统【uniapp+springboot+vue】2501_915921431 天前
HTTPS前端劫持 新一代流量劫持解决方案爱怪笑的小杰杰1 天前
优化 UniApp 日历组件的多语言切换:告别 setLocale 引起的 App 重启计算机学姐2 天前
基于微信小程序的宠物服务系统【uniapp+springboot+vue】2501_915909062 天前
iOS应用签名的三种方法全解析:从官方到第三方工具心中无石马2 天前
uniapp引入tailwindcss4.xfix一个write十个2 天前
【uniApp开发】微信小程序 web-view 内嵌 H5 跳转支付踩坑实录wuxianda10302 天前
苹果App上架4.3a被拒解决方案汇报总结西洼工作室2 天前
uniapp+vue3+python对接阿里云短信认证服务alibabacloud_dypnsapi20170525