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 天前
24小时自助健身房系统软件开发实战指南:功能设计与部署方案2501_916007474 天前
苹果商店iOS应用上架费用全面解析:开发者计划与审核费用计算2501_916008895 天前
如何实现iOS App代码混淆:SwiftShield使用指南2501_916008895 天前
怎么用 Godot 导出 iOS 应用并上架 App Store?签名字段该填什么?郑州光合科技余经理5 天前
同城外卖小程序开发:下单成功后,后台导出能不能对上用户端状态白远山6 天前
城市电竞陪玩调度系统实战:从派单算法到多端协同的架构拆解白远山6 天前
上海24小时自助健身房系统软件开发实战指南白远山7 天前
上海24小时自助健身房系统软件开发实战指南:从需求到部署海鸥两三8 天前
小程序文档预览 · 进阶面试题海鸥两三8 天前
微信小程序 PDF 预览实践(uni.downloadFile → uni.openDocument)