| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849 |
- import axios from 'axios'
- import { useAuthStore } from '../stores/auth'
- import { ElMessage } from 'element-plus'
- const api = axios.create({
- baseURL: '/api',
- timeout: 0, // 0 = no timeout
- headers: { 'Content-Type': 'application/json' },
- })
- api.interceptors.request.use((config) => {
- const auth = useAuthStore()
- if (auth.token) {
- config.headers.Authorization = `Bearer ${auth.token}`
- }
- return config
- })
- api.interceptors.response.use(
- (res) => {
- const body = res.data
- if (body.code !== 0 && body.code !== undefined) {
- ElMessage.error(body.msg || '请求失败')
- return Promise.reject(new Error(body.msg))
- }
- return body
- },
- (err) => {
- if (err.response?.status === 401) {
- const auth = useAuthStore()
- auth.logout()
- if (window.location.pathname !== '/login') {
- window.location.href = '/login'
- }
- } else if (err.response?.status === 403 && err.response?.data?.detail === '用户已被禁用') {
- const auth = useAuthStore()
- auth.logout()
- ElMessage.error('账号已被禁用,请联系管理员')
- if (window.location.pathname !== '/login') {
- window.location.href = '/login'
- }
- } else {
- ElMessage.error(err.response?.data?.detail || err.message || '网络异常')
- }
- return Promise.reject(err)
- },
- )
- export default api
|