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
相关推荐
不爱吃饭爱吃菜2 小时前
uniapp微信小程序一键授权登录明耀2 小时前
WPF C# 用WebView加载H5页面(uniapp项目,vue项目)timeguys12 小时前
【前端】[vue3] [uni-app]使用 vantUI 框架Aiden Targaryen14 小时前
Windows/MacOS WebStorm/IDEA 中开发 Uni-App 配置想要飞翔的pig15 小时前
uniapp+vue3页面滚动加载数据会功夫的李白15 小时前
uniapp自动构建pages.json的vite插件TE-茶叶蛋16 小时前
Uniapp、Flutter 和 React Native 全面对比特立独行的猫a19 小时前
uni-app 开发HarmonyOS的鸿蒙影视项目分享:从实战案例到开源后台七七小报1 天前
uniapp-商城-61-后台 新增商品(添加商品到数据库)hbcui19841 天前
uni-app x正式支持鸿蒙原生应用开发