Files
account/resources/mobile/utils/request.js
2026-01-19 11:19:44 +08:00

86 lines
2.0 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
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