86 lines
2.0 KiB
JavaScript
86 lines
2.0 KiB
JavaScript
import Request from 'luch-request'
|
||
import sysConfig from '@/config'
|
||
import tool from '@/utils/tool'
|
||
|
||
const request = new Request()
|
||
|
||
// 错误码常量
|
||
const ERROR_CODES = {
|
||
TOKEN_EXPIRED: 2000,
|
||
TOKEN_INVALID: 2001
|
||
}
|
||
|
||
// HTTP状态码处理映射
|
||
const HTTP_ERROR_MESSAGES = {
|
||
400: '请求参数错误',
|
||
401: '未授权,请重新登录',
|
||
403: '拒绝访问',
|
||
404: '请求地址不存在',
|
||
500: '服务器内部错误',
|
||
502: '网络连接失败',
|
||
503: '服务不可用',
|
||
504: '网关超时'
|
||
}
|
||
|
||
request.setConfig((config) => {
|
||
config.baseURL = sysConfig.baseURL
|
||
config.header = {
|
||
'content-type': 'application/json',
|
||
}
|
||
config.timeout = 30000
|
||
config.sslVerify = false
|
||
return config
|
||
})
|
||
|
||
request.interceptors.request.use((config) => {
|
||
// 从本地存储获取 token(避免循环依赖)
|
||
const token = tool.data.get('token') || ''
|
||
config.header.Authorization = `Bearer ${token}`
|
||
|
||
return config
|
||
}, (error) => {
|
||
return Promise.reject(error)
|
||
})
|
||
|
||
request.interceptors.response.use((response) => {
|
||
const { code, message } = response.data || {}
|
||
|
||
// 处理 token 过期或无效
|
||
if (code === ERROR_CODES.TOKEN_EXPIRED || code === ERROR_CODES.TOKEN_INVALID) {
|
||
uni.showToast({
|
||
icon: 'none',
|
||
title: message || '登录已过期,请重新登录',
|
||
duration: 1500
|
||
})
|
||
setTimeout(() => {
|
||
// 清除本地存储并跳转登录页
|
||
uni.removeStorageSync('token')
|
||
uni.removeStorageSync('is-login')
|
||
uni.removeStorageSync('userInfo')
|
||
uni.reLaunch({
|
||
url: '/pages/ucenter/login/index'
|
||
})
|
||
}, 1500)
|
||
return Promise.reject(response.data)
|
||
}
|
||
|
||
return response.data
|
||
}, (error) => {
|
||
const { statusCode, errMsg } = error || {}
|
||
const errorMessage = HTTP_ERROR_MESSAGES[statusCode] || errMsg || '请求失败,请稍后重试'
|
||
|
||
if (statusCode === 401) {
|
||
// 清除本地存储并跳转登录页
|
||
uni.removeStorageSync('token')
|
||
uni.removeStorageSync('is-login')
|
||
uni.removeStorageSync('userInfo')
|
||
uni.reLaunch({
|
||
url: '/pages/ucenter/login/index'
|
||
})
|
||
}
|
||
|
||
return Promise.reject(error)
|
||
})
|
||
|
||
export default request
|