Преглед на файлове

feat(apiClient): 添加请求和响应拦截器

- 在 apiClient 中添加了请求拦截器,可以在发送请求前进行处理,如添加 token
- 添加了响应拦截器,可以对响应数据进行处理,如返回特定格式的数据
-拦截器的添加提高了 API客户端的灵活性和可扩展性
nahida преди 1 година
родител
ревизия
af63dc4d97
променени са 1 файла, в които са добавени 40 реда и са изтрити 0 реда
  1. 40 0
      src/utils/apiClient.js

+ 40 - 0
src/utils/apiClient.js

@@ -10,6 +10,46 @@ const apiClient = axios.create({
 
 console.log(import.meta.env.VITE_APP_BASE_API_OTHER);
 
+// 请求拦截器
+apiClient.interceptors.request.use(
+  config => {
+    // 在发送请求之前做些什么,比如添加token
+    // const token = localStorage.getItem('token'); // 假设token存储在localStorage中
+    // if (token) {
+    //   config.headers.Authorization = `Bearer ${token}`;
+    // }
+    return config;
+  },
+  error => {
+    // 对请求错误做些什么
+    return Promise.reject(error);
+  }
+);
+
+// 响应拦截器
+apiClient.interceptors.response.use(
+  response => {
+    // 对响应数据做点什么
+    return response.data;
+  },
+  error => {
+    // 对响应错误做点什么
+    // if (error.response) {
+    //   // 请求已发出但服务器响应的状态码不在2xx范围内
+    //   console.error('Response Error:', error.response.data);
+    //   console.error('Status Code:', error.response.status);
+    //   console.error('Headers:', error.response.headers);
+    // } else if (error.request) {
+    //   // 请求已发出,但没有收到响应
+    //   // console.error('Request Error:', error.request);
+    // } else {
+    //   // 一些设置请求时发生错误
+    //   // console.error('Error:', error.message);
+    // }
+    return Promise.reject(error);
+  }
+);
+
 // 对外暴露的方法
 
 export function clientGet(endpoint, config = {}) {