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
相关推荐
AI多Agent协作实战派20 分钟前
AI多Agent协作系统实战(二十八):顶栏统一战争——从1个页面异常到31个页面全量对齐00后程序员张33 分钟前
iOS加固技术路线全面解析:Bitcode模式、源码模式与汇编模式对比及爱加密优势2501_9160088917 小时前
iOS IPA文件反编译与打包操作方法,拆包分析防护和加固打包name好难取诶1 天前
通过对云基座和离线基座的对比,帮助开发者理解如何在不同场景下选择合适的打包方案。 什么是“基座” 在 UniApp 中,基座(也称“ ...2501_915921431 天前
iOS手游安全反外挂解决方案:基于Xcode的加固混淆特色详解2501_916007471 天前
iOS App分发教程 App Store、TestFlight 与 Ad Hoc 的配置与上传方法qq_316837751 天前
uniapp 打包APP 使用 Galacean Effects 的特效古韵2 天前
你的 uni-app 分页,一个 hook 搞定竞态和加载游戏开发爱好者82 天前
iOS应用加固方案全解析:源码加固与IPA在线加固对比满栀5852 天前
uni-app 小程序开发实战:从路由踩坑、数据对接到 UI 优化的全方位复盘