AI_Painting_V2.0/src/utils/request.js
WangLeo 4255641158 fix: 重构认证接口 — 用户信息改用 /login/validateToken,token 校验改用 /auth/check/token/{token}
- getUserInfo: GET /sysUser/currentUser → POST /login/validateToken
- checkUsertoken: POST /login/validateToken → GET /auth/check/token/{token}
- checkTokenValid 传入当前 token 作为 URL 路径参数
- 更新 401 排除逻辑,同时排除两个认证接口防止死循环
2026-06-17 11:32:11 +08:00

84 lines
2.4 KiB
JavaScript

import axios from 'axios'
import { getToken } from '@/utils/auth'
import { userError } from './tokenError'
// 创建axios实例
const service = axios.create({
baseURL: import.meta.env.VITE_API_BASE_URL,
timeout: 50000 // 请求超时时间
})
const StatusCodeMessage = {
200: '服务器成功返回请求的数据',
201: '新建或修改数据成功。',
202: '一个请求已经进入后台排队(异步任务)',
204: '删除数据成功',
400: '请求错误(400)',
401: '未授权,请重新登录(401)',
403: '拒绝访问(403)',
404: '请求出错(404)',
408: '请求超时(408)',
500: '服务器错误(500)',
501: '服务未实现(501)',
502: '网络错误(502)',
503: '服务不可用(503)',
504: '网络超时(504)'
}
// request拦截器
service.interceptors.request.use(
(config) => {
const token = getToken()
if (!config.headers) {
config.headers = {}
}
if (token) config.headers.Authorization = `Bearer ${token}`
if (config.url?.startsWith(import.meta.env.VITE_API_TASK_PREFIX)) { // 算力调度后端
config.baseURL = import.meta.env.VITE_API_TASK_TARGET
} else if (config.url?.startsWith(import.meta.env.VITE_API_PAY_PREFIX)) { // 支付服务路由
config.baseURL = import.meta.env.VITE_API_PAY_TARGET
} else if (config.url?.startsWith(import.meta.env.VITE_API_AIGC_PREFIX)) { // 资源服务路由
config.baseURL = import.meta.env.VITE_API_AIGC_TARGET
}
return config
},
(error) => {
// Do something with request error
Promise.reject(error)
}
)
// response 拦截器
service.interceptors.response.use(
(response) => {
const { data } = response
const { success, code, status, msg, message } = data
if (success || code === 0 || status === 0) {
console.log('msg: \n', msg)
return response.data
} else if (code === 401 && !(response.config.url || '').includes('/auth/check/token/') && response.config.url !== '/login/validateToken') { // token 校验和获取用户信息接口返回 401 时不触发刷新,防止死循环
userError()
}
console.log('CodeMessage: \n', StatusCodeMessage[code])
console.log('msg: \n', msg)
return response.data
},
(error) => {
console.log('err: \n', error)
return Promise.reject(error)
}
)
// 添加HTTP DELETE方法
service.del = function (url, config) {
return service({
method: 'delete',
url,
...config
})
}
export default service