|
|
@@ -1,33 +1,55 @@
|
|
|
-// 创建axios实例配置
|
|
|
-import axios from 'axios';
|
|
|
-
|
|
|
+// src/utils/http.js
|
|
|
+import axios from "axios";
|
|
|
+import { ElMessage } from "element-plus";
|
|
|
+// 创建 axios 实例
|
|
|
const service = axios.create({
|
|
|
- baseURL: "http://127.0.0.1:8080/", // 从环境变量获取基础URL
|
|
|
- timeout: 5000 // 请求超时时间
|
|
|
+ baseURL: "/api", // 修改为基础 API 地址
|
|
|
+ timeout: 5000, // 超时时间
|
|
|
+ headers: { "Content-Type": "application/json;charset=utf-8" },
|
|
|
});
|
|
|
-
|
|
|
// 请求拦截器
|
|
|
service.interceptors.request.use(
|
|
|
- config => {
|
|
|
- // 在发送请求之前做些什么,例如添加token
|
|
|
+ (config) => {
|
|
|
+ // 可在此处添加 token 或其他请求头信息
|
|
|
+ // const token = localStorage.getItem('token');
|
|
|
+ // if (token) {
|
|
|
+ // config.headers['Authorization'] = `Bearer ${token}`;
|
|
|
+ // }
|
|
|
return config;
|
|
|
},
|
|
|
- error => {
|
|
|
- // 处理请求错误
|
|
|
+ (error) => {
|
|
|
+ // 请求错误处理
|
|
|
+ console.error("Request Error:", error);
|
|
|
return Promise.reject(error);
|
|
|
}
|
|
|
);
|
|
|
-
|
|
|
// 响应拦截器
|
|
|
service.interceptors.response.use(
|
|
|
- response => {
|
|
|
- // 对响应数据做点什么
|
|
|
- return response.data;
|
|
|
+ (response) => {
|
|
|
+ // 对响应数据做处理
|
|
|
+ const res = response.data;
|
|
|
+ // 如果返回的状态码不是 200,提示错误
|
|
|
+ if (res.code !== 200) {
|
|
|
+ ElMessage.error(res.message || "Error");
|
|
|
+ return Promise.reject(new Error(res.message || "Error"));
|
|
|
+ } else {
|
|
|
+ return res;
|
|
|
+ }
|
|
|
},
|
|
|
- error => {
|
|
|
- // 处理响应错误
|
|
|
+ (error) => {
|
|
|
+ // ⽹络错误或服务未响应
|
|
|
+ console.error("Response Error:", error);
|
|
|
+ if (error.response) {
|
|
|
+ // 服务器返回了状态码
|
|
|
+ ElMessage.error(`请求失败,状态码: ${error.response.status}`);
|
|
|
+ } else if (error.request) {
|
|
|
+ // 请求已发出但没有收到响应
|
|
|
+ ElMessage.error("⽹络连接失败,请检查您的⽹络");
|
|
|
+ } else {
|
|
|
+ // 其他错误
|
|
|
+ ElMessage.error("未知错误");
|
|
|
+ }
|
|
|
return Promise.reject(error);
|
|
|
}
|
|
|
);
|
|
|
-
|
|
|
-export default service;
|
|
|
+export default service;
|