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
相关推荐
郑州光合科技余经理4 小时前
乡镇外卖跑腿小程序开发实战:基于PHP的乡镇同城O2O2501_9160088912 小时前
iOS 跨平台开发实战指南,从框架选择到开心上架(Appuploader)跨系统免 Mac 发布全流程解析QuantumLeap丶1 天前
《uni-app跨平台开发完全指南》- 06 - 页面路由与导航用户9714171814271 天前
uniapp页面路由Kingsaj1 天前
uni-app打包app -- 在用户首次启动 App 时,强制弹出一个“用户协议与隐私政策”的确认对话框。Vue10241 天前
uniapp 使用renderjs 封装 video-player 视频播放器, html5视频播放器-解决视频层级、覆盖、播放卡顿钱端工程师1 天前
uniapp封装uni.request请求,实现重复接口请求中断上次请求(防抖)茶憶1 天前
uni-app app移动端实现纵向滑块功能,并伴随自动播放dcloud_jibinbin1 天前
【uniapp】解决小程序分包下的json文件编译后生成到主包的问题茶憶1 天前
uniapp移动端实现触摸滑动功能:上下滑动展开收起内容,左右滑动删除列表