liqiuying 2 ماه پیش
والد
کامیت
7afd92612e
2فایلهای تغییر یافته به همراه235 افزوده شده و 68 حذف شده
  1. 104 0
      components/utils/request.ts
  2. 131 68
      entrypoints/popup/pages/Login.tsx

+ 104 - 0
components/utils/request.ts

@@ -0,0 +1,104 @@
+// utils/request.ts
+interface RequestOptions extends RequestInit {
+  params?: Record<string, any>;
+  timeout?: number;
+}
+
+class Request {
+  private baseUrl: string;
+  private timeout: number;
+
+  constructor(baseUrl: string = '', timeout: number = 10000) {
+    this.baseUrl = baseUrl;
+    this.timeout = timeout;
+  }
+
+  private getUrl(url: string): string {
+    if (url.startsWith('http')) return url;
+    return this.baseUrl + url;
+  }
+
+  private async handleResponse(response: Response) {
+    if (!response.ok) {
+      throw new Error(`HTTP error! status: ${response.status}`);
+    }
+    return response.json();
+  }
+
+  private async withTimeout<T>(promise: Promise<T>, timeout: number): Promise<T> {
+    return Promise.race([
+      promise,
+      new Promise<never>((_, reject) =>
+        setTimeout(() => reject(new Error('Request timeout')), timeout)
+      )
+    ]);
+  }
+
+  async request<T = any>(url: string, options: RequestOptions = {}): Promise<T> {
+    const { 
+      method = 'GET', 
+      headers = {}, 
+      body, 
+      params,
+      timeout = this.timeout,
+      ...restOptions 
+    } = options;
+
+    let fullUrl = this.getUrl(url);
+    
+    // 处理查询参数
+    if (params) {
+      const searchParams = new URLSearchParams(params);
+      fullUrl += (fullUrl.includes('?') ? '&' : '?') + searchParams.toString();
+    }
+
+    const config: RequestInit = {
+      method,
+      headers: {
+        'Content-Type': 'application/json',
+        ...headers
+      },
+      ...restOptions
+    };
+
+    if (body) {
+      config.body = typeof body === 'string' ? body : JSON.stringify(body);
+    }
+
+    try {
+      const response = await this.withTimeout(fetch(fullUrl, config), timeout);
+      return await this.handleResponse(response);
+    } catch (error) {
+      throw error;
+    }
+  }
+
+  get<T = any>(url: string, options?: Omit<RequestOptions, 'method'>) {
+    return this.request<T>(url, { ...options, method: 'GET' });
+  }
+
+  post<T = any>(url: string, data?: any, options?: Omit<RequestOptions, 'method' | 'body'>) {
+    return this.request<T>(url, { 
+      ...options, 
+      method: 'POST', 
+      body: data 
+    });
+  }
+
+  put<T = any>(url: string, data?: any, options?: Omit<RequestOptions, 'method' | 'body'>) {
+    return this.request<T>(url, { 
+      ...options, 
+      method: 'PUT', 
+      body: data 
+    });
+  }
+
+  delete<T = any>(url: string, options?: Omit<RequestOptions, 'method'>) {
+    return this.request<T>(url, { ...options, method: 'DELETE' });
+  }
+}
+
+// 创建默认实例
+const request = new Request('https://user.landwu.com/api');
+
+export default request;

+ 131 - 68
entrypoints/popup/pages/Login.tsx

@@ -5,6 +5,7 @@ import { Input, Loading, Form, Grid } from '@alifd/next';
 const { Row, Col } = Grid
 import { CustomMessage } from '@/components/CustomMessage'
 import { useLoading } from '@/components/LoadingContext';
+import request from '@/components/utils/request'
 
 export default function Login({ setIsLoggedIn }: { setIsLoggedIn: (loggedIn: boolean) => void }) {
     const formRef = useRef<any>(null);
@@ -67,86 +68,78 @@ export default function Login({ setIsLoggedIn }: { setIsLoggedIn: (loggedIn: boo
         return Object.keys(newErrors).length === 0;
     };
 
-    const evVerify = () => {
-        fetch('https://user.landwu.com/api/user/verify', {
-            method: 'POST',
-            headers: {
-                'Content-Type': 'application/json',
-            }
-        }).then(resjson => {
-            return resjson.json();
-        }).then(res => {
+    // const evVerify = () => {
+    //     fetch('https://user.landwu.com/api/user/verify', {
+    //         method: 'POST',
+    //         headers: {
+    //             'Content-Type': 'application/json',
+    //         }
+    //     }).then(resjson => {
+    //         return resjson.json();
+    //     }).then(res => {
+    //         const { data = {} } = res;
+    //         const { data: info = {} } = data;
+    //         const { key = "", img = "" } = info;
+    //         setKeys(key)
+    //         setValidImg(img)
+    //     })
+    // }
+
+    const evVerify = async () => {
+        try {
+            const res = await request.post('/user/verify');
             const { data = {} } = res;
             const { data: info = {} } = data;
             const { key = "", img = "" } = info;
-            setKeys(key)
-            setValidImg(img)
-        })
-    }
+            setKeys(key);
+            setValidImg(img);
+        } catch (error) {
+            CustomMessage.error('获取验证码失败');
+        }
+    };
+
+    const handleLogin = async (values: any) => {
+        if (!validateForm()) return;
 
-    const handleLogin = (values: any) => {
-        if (!validateForm()) return
         try {
-            // setLoading(true);
             showLoading('登录中...');
+
             const params = {
                 ...values,
                 key: keys
+            };
+
+            const res = await request.post('/user/login', params);
+            const { msg = "", token = "", code } = res;
+
+            if (!code) {
+                hideLoading();
+                return false;
             }
-            // 发送登录请求
-            fetch('https://user.landwu.com/api/user/login', {
-                method: 'POST',
-                headers: {
-                    'Content-Type': 'application/json',
-                },
-                body: JSON.stringify(params),
-            }).then(response => response.json()).then(res => {
-                const { msg = "", token = "", code } = res;
-                if (!code) {
-                    // setLoading(false);
-                    hideLoading();
-                    return false;
-                }
 
-                if (code == -1) {
-                    evVerify()
-                    CustomMessage.error(msg);
-                    // setLoading(false);
-                    hideLoading();
-                    return false;
-                }
-                fetch('https://user.landwu.com/api/user/getProfile', {
-                    method: 'POST',
-                    headers: {
-                        'Content-Type': 'application/json',
-                    },
-                    body: JSON.stringify({ api_token: token }),
-                }).then(response => response.json()).then(res => {
-                    if (res.code == 1) {
-                        const { data = {} } = res;
-                        const { userinfo = {} } = data;
-                        const userinfo_str = JSON.stringify(userinfo);
-                        localStorage.setItem('userinfo', userinfo_str);
-                        CustomMessage.success(msg);
-                        localStorage.setItem("access_token", token);
-                        localStorage.setItem('isLoggedIn', 'true');
-                        setTimeout(() => {
-                            // setLoading(false);
-                            hideLoading();
-                            setIsLoggedIn(true);
-                            // 跳转到首页
-                            navigate('/');
-                        }, 100)
-                    }
-                }).catch(err => {
-                    // setLoading(false);
-                    hideLoading();
-                })
-            }).catch((e) => {
-                console.log("catch")
-                // setLoading(false);
+            if (code == -1) {
+                evVerify();
+                CustomMessage.error(msg);
                 hideLoading();
-            });
+                return false;
+            }
+
+            const profileRes = await request.post('/user/getProfile', {api_token: token});
+            if (profileRes.code == 1) {
+                const { data = {} } = profileRes;
+                const { userinfo = {} } = data;
+                const userinfo_str = JSON.stringify(userinfo);
+                localStorage.setItem('userinfo', userinfo_str);
+                CustomMessage.success(msg);
+                localStorage.setItem("access_token", token);
+                localStorage.setItem('isLoggedIn', 'true');
+
+                setTimeout(() => {
+                    hideLoading();
+                    setIsLoggedIn(true);
+                    navigate('/');
+                }, 100);
+            }
         } catch (error) {
             console.error('登录请求失败:', error);
             CustomMessage.error('网络错误,请稍后重试');
@@ -154,6 +147,76 @@ export default function Login({ setIsLoggedIn }: { setIsLoggedIn: (loggedIn: boo
         }
     };
 
+    // const handleLogin = (values: any) => {
+    //     if (!validateForm()) return
+    //     try {
+    //         // setLoading(true);
+    //         showLoading('登录中...');
+    //         const params = {
+    //             ...values,
+    //             key: keys
+    //         }
+    //         // 发送登录请求
+    //         fetch('https://user.landwu.com/api/user/login', {
+    //             method: 'POST',
+    //             headers: {
+    //                 'Content-Type': 'application/json',
+    //             },
+    //             body: JSON.stringify(params),
+    //         }).then(response => response.json()).then(res => {
+    //             const { msg = "", token = "", code } = res;
+    //             if (!code) {
+    //                 // setLoading(false);
+    //                 hideLoading();
+    //                 return false;
+    //             }
+
+    //             if (code == -1) {
+    //                 evVerify()
+    //                 CustomMessage.error(msg);
+    //                 // setLoading(false);
+    //                 hideLoading();
+    //                 return false;
+    //             }
+    //             fetch('https://user.landwu.com/api/user/getProfile', {
+    //                 method: 'POST',
+    //                 headers: {
+    //                     'Content-Type': 'application/json',
+    //                 },
+    //                 body: JSON.stringify({ api_token: token }),
+    //             }).then(response => response.json()).then(res => {
+    //                 if (res.code == 1) {
+    //                     const { data = {} } = res;
+    //                     const { userinfo = {} } = data;
+    //                     const userinfo_str = JSON.stringify(userinfo);
+    //                     localStorage.setItem('userinfo', userinfo_str);
+    //                     CustomMessage.success(msg);
+    //                     localStorage.setItem("access_token", token);
+    //                     localStorage.setItem('isLoggedIn', 'true');
+    //                     setTimeout(() => {
+    //                         // setLoading(false);
+    //                         hideLoading();
+    //                         setIsLoggedIn(true);
+    //                         // 跳转到首页
+    //                         navigate('/');
+    //                     }, 100)
+    //                 }
+    //             }).catch(err => {
+    //                 // setLoading(false);
+    //                 hideLoading();
+    //             })
+    //         }).catch((e) => {
+    //             console.log("catch")
+    //             // setLoading(false);
+    //             hideLoading();
+    //         });
+    //     } catch (error) {
+    //         console.error('登录请求失败:', error);
+    //         CustomMessage.error('网络错误,请稍后重试');
+    //         hideLoading();
+    //     }
+    // };
+
     return (
         <div className="bg-gray-50 p-4">
             <div className="text-center mb-6">