This commit is contained in:
2025-01-03 17:32:02 +08:00
commit bec8d97242
576 changed files with 152154 additions and 0 deletions
+66
View File
@@ -0,0 +1,66 @@
import axios from 'axios'
import { UniAdapter } from 'uniapp-axios-adapter'
// 创建axios实例
const service = axios.create({
baseURL: process.env.VUE_APP_BASE_API || '/api', // api的base_url
timeout: 15000, // 请求超时时间
adapter: UniAdapter, // 使用uni-app的适配器
headers: {
'Content-Type': 'application/json;charset=utf-8'
}
})
// 请求拦截器
service.interceptors.request.use(
config => {
// 在发送请求之前做些什么
const token = uni.getStorageSync('token')
if (token) {
config.headers['Authorization'] = `Bearer ${token}`
}
return config
},
error => {
// 对请求错误做些什么
console.error('请求错误:', error)
return Promise.reject(error)
}
)
// 响应拦截器
service.interceptors.response.use(
response => {
const res = response.data
// 这里可以根据后端返回的状态码做相应的处理
if (res.code !== 200) {
uni.showToast({
title: res.message || '错误',
icon: 'none',
duration: 2000
})
// 401: 未登录或token过期
if (res.code === 401) {
uni.removeStorageSync('token')
// 跳转登录页
uni.reLaunch({
url: '/pages/login/login'
})
}
return Promise.reject(res)
}
return res
},
error => {
console.error('响应错误:', error)
uni.showToast({
title: error.message || '网络异常',
icon: 'none',
duration: 2000
})
return Promise.reject(error)
}
)
export default service