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
相关推荐
2501_9160074717 小时前
网站爬虫原理,基于浏览器点击行为还原可接口请求Можно19 小时前
uni.request 和 axios 的区别?前端请求库全面对比woshinon1 天前
【Uniapp(HBuilderX)针对微信小程序和H5平台实现差异化配置(自定义发行)】蜡台1 天前
Uniapp H5Builderx 预览Html 显示404问题解决Можно1 天前
pages.json 和 manifest.json 有什么作用?uni-app 核心配置文件详解2501_915106321 天前
iOS 多技术栈混淆实现,跨平台 App 混淆拆解与组合爱看老照片1 天前
uniapp传递数值(数字)时需要使用v-bind的形式(加上冒号)huycheaven1 天前
uniapp-x生成App条形码和二维码00后程序员张1 天前
有些卡顿不是 CPU 的问题,还要排查磁盘 I/OAftery的博客1 天前
HBulider项目打包上传到App Store需要的证书和私钥文件