Files
biji/biji-qianduan/src/utils/axios.js
ikmkj 9af5154973 refactor(biji-qianduan): 优化 axios 响应拦截和错误处理
- 在 axios响应拦截器中增加对非 200 状态码的处理
- 修改 RegisterPage 组件中的错误处理方式,直接使用 error.message
2025-08-01 19:33:51 +08:00

48 lines
1.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 axios from 'axios'
import { useUserStore } from '../stores/user'
const instance = axios.create({
baseURL: import.meta.env.VITE_API_BASE_URL,
// 开发环境使用withCredentials生产环境关闭
withCredentials: import.meta.env.DEV,
headers: {
'Content-Type': 'application/json'
}
})
// 请求拦截器
instance.interceptors.request.use(
config => {
const userStore = useUserStore()
if (userStore.token) {
config.headers['Authorization'] = `Bearer ${userStore.token}`
}
return config
},
error => {
return Promise.reject(error)
}
)
// 响应拦截器
instance.interceptors.response.use(
response => {
const res = response.data;
if (res.code !== 200) {
// ElMessage({
// message: res.msg || 'Error',
// type: 'error',
// duration: 5 * 1000
// });
return Promise.reject(new Error(res.msg || 'Error'));
} else {
return res.data;
}
},
error => {
return Promise.reject(error)
}
)
export default instance