56 lines
1.5 KiB
JavaScript
56 lines
1.5 KiB
JavaScript
import axios from 'axios'
|
|
import { useMessage } from '@/components/messages/useAlert';
|
|
import router from '@/router';
|
|
import { useAuthStore } from '@/stores/auth';
|
|
|
|
const message = useMessage();
|
|
const authStore = useAuthStore();
|
|
|
|
const api = axios.create({
|
|
baseURL: import.meta.env.VITE_API_BASE_URL || 'http://localhost:3000/api', // 从环境变量中读取基础 URL
|
|
timeout: 10000,
|
|
headers: {
|
|
'Content-Type': 'application/json',
|
|
}
|
|
})
|
|
|
|
api.interceptors.request.use(
|
|
config => {
|
|
const token = authStore.token;
|
|
if (token) {
|
|
config.headers.Authorization = `Bearer ${token}`;
|
|
}
|
|
return config;
|
|
},
|
|
err => {
|
|
return Promise.reject(err);
|
|
}
|
|
)
|
|
|
|
api.interceptors.response.use(
|
|
response => {
|
|
return response.data;
|
|
},
|
|
err => {
|
|
if (err.response) {
|
|
switch (err.response.status) {
|
|
case 401:
|
|
message.error('未登录,请登录后操作。');
|
|
router.push('/auth/login')
|
|
break;
|
|
default:
|
|
message.error('请求错误,请检查网络。');
|
|
break;
|
|
}
|
|
}
|
|
return Promise.reject(err);
|
|
}
|
|
)
|
|
|
|
export const request = {
|
|
get: (url, config) => api.get(url, config),
|
|
post: (url, data, config) => api.post(url, data, config),
|
|
put: (url, data, config) => api.put(url, data, config),
|
|
delete: (url, config) => api.delete(url, config),
|
|
instance: api,
|
|
}; |