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_9160074714 小时前
iOS应用性能优化全面指南:从内存管理到工具使用巴博尔1 天前
UNIAPP中NVUE页面 动画边界条件╝2 天前
uniapp 深度使用路光.2 天前
uniapp小程序/App使用webview打通麦克风权限实现录音功能xiaoyan20152 天前
全新首发uniapp+deepseek-v4三端通用智能ai助手anyup2 天前
【最全鸿蒙】uni-app 转鸿蒙:从打包失败到商店上架成功全过程2501_915106322 天前
深入解析HTTPS抓包原理、中间人攻击及反抓包技术攻防游戏开发爱好者82 天前
React Grab工具详解:AI助力Vue3、Svelte和Solid前端元素调试sN2vuQ08W2 天前
uni-app 实现视频聊天、屏幕分享,支持Android、HarmonyOS、iOS遗憾随她而去.2 天前
uniapp App平台 真机运行