Procházet zdrojové kódy

refactor(simple-demo): 重构登录功能并优化 memos 页面

- 重构 login.js 文件,提取公共函数并优化代码结构
- 在 memos.html 中引入外部样式表,移除内联样式
- 修改 checkLogin 函数,增加登录失败时的处理逻辑
- 调整 memos 页面的授权逻辑,使用 cookie 中的 token
tianyun před 5 měsíci
rodič
revize
82d4d65f9c
3 změnil soubory, kde provedl 120 přidání a 135 odebrání
  1. 50 40
      simple-demo/js/login.js
  2. 63 0
      simple-demo/memos.css
  3. 7 95
      simple-demo/memos.html

+ 50 - 40
simple-demo/js/login.js

@@ -1,47 +1,57 @@
-function checkLogin() {
-    const loginId = getCookie('loginId');
-    if (loginId) {
-        // 如果 cookie 中有 loginId,说明用户已经登录,直接放行
-        return true;
-    } else {
-        // 如果没有 loginId,弹出登录框
-        const username = prompt('请输入用户名');
-        const password = prompt('请输入密码');
-        // 发送登录请求
-        const xhr = new XMLHttpRequest();
-        xhr.open('POST', 'https://php.tianyunperfect.cn/controller/user.php?action=login', false);
-        xhr.setRequestHeader('Content-Type', 'application/json');
-        xhr.send(JSON.stringify({
-            username,
-            password
-        }));
-        const response = JSON.parse(xhr.responseText);
-        if (response.code === 200) {
-            // 登录成功,设置 loginId 的 cookie,并放行
-            setCookie('loginId', response.data.token, 30);
-            return true;
-        } else {
-            // 登录失败,弹出错误提示
-            alert(response.message);
-            return false;
-        }
-    }
-}
+let tokenKeyStr = "token";
 
 function getCookie(name) {
-    const cookies = document.cookie.split(';');
-    for (let i = 0; i < cookies.length; i++) {
-        const cookie = cookies[i].trim();
-        if (cookie.startsWith(name + '=')) {
-            return cookie.substring(name.length + 1);
-        }
+  const cookies = document.cookie.split(";");
+  for (let i = 0; i < cookies.length; i++) {
+    const cookie = cookies[i].trim();
+    if (cookie.startsWith(name + "=")) {
+      return cookie.substring(name.length + 1);
     }
-    return null;
+  }
+  return null;
 }
 
 function setCookie(name, value, days) {
-    const expires = new Date();
-    expires.setTime(expires.getTime() + days * 24 * 60 * 60 * 1000);
-    document.cookie = name + '=' + value + ';expires=' + expires.toUTCString();
+  const expires = new Date();
+  expires.setTime(expires.getTime() + days * 24 * 60 * 60 * 1000);
+  document.cookie = name + "=" + value + ";expires=" + expires.toUTCString();
+}
+
+function checkLogin() {
+  const loginId = getCookie(tokenKeyStr);
+  if (loginId) {
+    // 如果 cookie 中有 loginId,说明用户已经登录,直接放行
+    return true;
+  } else {
+    // 如果没有 loginId,弹出登录框
+    const username = prompt("请输入用户名");
+    const password = prompt("请输入密码");
+    // 发送登录请求
+    const xhr = new XMLHttpRequest();
+    xhr.open(
+      "POST",
+      "https://php.tianyunperfect.cn/controller/user.php?action=login",
+      false
+    );
+    xhr.setRequestHeader("Content-Type", "application/json");
+    xhr.send(
+      JSON.stringify({
+        username,
+        password,
+      })
+    );
+    const response = JSON.parse(xhr.responseText);
+    if (response.code === 200) {
+      setCookie(tokenKeyStr, response.data.token, 30);
+      return true;
+    } else {
+      // 登录失败,弹出错误提示
+      alert(response.message);
+      // 删除token
+      setCookie(tokenKeyStr, "", -1);
+      return false;
+    }
+  }
 }
-checkLogin();
+
+checkLogin();

+ 63 - 0
simple-demo/memos.css

@@ -0,0 +1,63 @@
+body {
+        font-family: Lyon-Text, Georgia, "Songti SC", SimSun, serif;
+      }
+
+      .vditor-reset {
+        font-family: Lyon-Text, Georgia, "Songti SC", SimSun, serif !important;
+      }
+
+      img {
+        border: 1px solid #b7b6b6;
+      }
+
+      .img {
+        border: 1px solid #b7b6b6;
+        max-width: 200px;
+        max-height: 200px;
+        margin: 10px 10px 0 0 !important;
+        cursor: pointer;
+      }
+
+      .editClass button {
+        display: inline;
+        /*margin-top: 5px;*/
+        margin-left: 30px;
+      }
+
+      .contentLine div {
+        margin: 5px 0 0;
+      }
+
+      .border {
+        /*border: 1px solid #b7b6b6;*/
+        border-radius: 5px;
+        padding: 10px;
+        background-color: white;
+      }
+
+      body {
+        background-color: #f4f4f5;
+      }
+
+      .myTop {
+        position: fixed;
+        top: 0;
+        background-image: url("./img/gray.png");
+        /*    背景铺满整个div*/
+        background-size: 100% 100%;
+        width: 100%;
+        padding: 10px;
+        z-index: 100;
+      }
+
+      .myText {
+        border: 1px solid #d2d2d2;
+      }
+
+      .vditor-reset {
+        padding: 10px 20px !important;
+      }
+
+      .vditor-toolbar {
+        display: none;
+      }

+ 7 - 95
simple-demo/memos.html

@@ -10,71 +10,7 @@
 
     <script src="js/util.js"></script>
     <script src="js/login.js"></script>
-    <style>
-      body {
-        font-family: Lyon-Text, Georgia, "Songti SC", SimSun, serif;
-      }
-
-      .vditor-reset {
-        font-family: Lyon-Text, Georgia, "Songti SC", SimSun, serif !important;
-      }
-
-      img {
-        border: 1px solid #b7b6b6;
-      }
-
-      .img {
-        border: 1px solid #b7b6b6;
-        max-width: 200px;
-        max-height: 200px;
-        margin: 10px 10px 0 0 !important;
-        cursor: pointer;
-      }
-
-      .editClass button {
-        display: inline;
-        /*margin-top: 5px;*/
-        margin-left: 30px;
-      }
-
-      .contentLine div {
-        margin: 5px 0 0;
-      }
-
-      .border {
-        /*border: 1px solid #b7b6b6;*/
-        border-radius: 5px;
-        padding: 10px;
-        background-color: white;
-      }
-
-      body {
-        background-color: #f4f4f5;
-      }
-
-      .myTop {
-        position: fixed;
-        top: 0;
-        background-image: url("./img/gray.png");
-        /*    背景铺满整个div*/
-        background-size: 100% 100%;
-        width: 100%;
-        padding: 10px;
-        z-index: 100;
-      }
-
-      .myText {
-        border: 1px solid #d2d2d2;
-      }
-
-      .vditor-reset {
-        padding: 10px 20px !important;
-      }
-
-      .vditor-toolbar {
-        display: none;
-      }
-    </style>
+    <link rel="stylesheet" href="memos.css" />
     <script src="js/vue.min.js"></script>
     <script src="elementUI/index.js"></script>
     <link rel="stylesheet" href="elementUI/index.css" />
@@ -428,19 +364,11 @@
         </span>
       </el-dialog>
     </div>
-    <!-- 引入Quill库 -->
-    <!--<script src="./js/cdn.quilljs.com_1.3.6_quill.js"></script>-->
     <!--异步请求示例:requestUtil.sync('https://jsonplaceholder.typicode.com/posts/1', 'post', data, headers) .then(data => console.log(data))-->
     <script>
-      // if (getQueryString("id") !== "tianyunperfect") {
-      //     // location.href = "http://127.0.0.1";
-      // }
-
-      let authStr =
-        "bearer eyJhbGciOiJIUzI1NiIsImtpZCI6InYxIiwidHlwIjoiSldUIn0.eyJuYW1lIjoidGlhbnl1bnBlcmZlY3QiLCJpc3MiOiJtZW1vcyIsInN1YiI6IjEiLCJhdWQiOlsidXNlci5hY2Nlc3MtdG9rZW4iXSwiaWF0IjoxNzA5MTc5NTUyfQ.LFxWB4efya1sL7VoJ42xpXxbAip-udT_Kx2OwZ8Y3-E";
       let myHeaders = {
         "Content-type": "application/json",
-        Authorization: authStr,
+        Authorization: "",
       };
 
       function getRandomId() {
@@ -486,33 +414,17 @@
               console.log(2);
               this.contentList.forEach((item) => {
                 this.resetView(item);
-                // let ed = new Vditor(item.resource_name, {
-                //     cdn: 'https://ld246.com/js/lib/vditor',
-                //     // height: 360,
-                //     toolbarConfig: {
-                //         pin: true,
-                //     },
-                //     // preview: {
-                //     //     theme:{
-                //     //         path: ''
-                //     //     }
-                //     // },
-                //     theme: 'classic',
-                //     cache: {
-                //         enable: false,
-                //     },
-                //     after: () => {
-                //         ed.setValue(item.content)
-                //     },
-                // })
               });
             });
           },
         },
         mounted() {
           if (!checkLogin()) {
-            return;
+            // 警告并刷新页面
+            alert("登录失败,请先登录");
+            location.reload();
           }
+          myHeaders.Authorization = "bearer " + getCookie("token");
           if (this.getQueryStr()) {
             this.searchStr = this.getQueryStr();
           }
@@ -1008,7 +920,7 @@
               { ids: ids },
               {}
             );
-            // {'code': 200, 'res': [{'memo_id': 1, 'resource_name': 'EfdmvRsodBviDQWRmDiTaV'}, {'memo_id': 4, 'resource_name': '2rY5kmn3AHsy23vK4vSskV'}, {'memo_id': 7, 'resource_name': 'FMhzJXjoTa7fdtbbCBjXnt'}]}
+            // {'code': 200, 'res': [{'memo_id': 1, 'resource_name': 'EfdmvRsodBviDQWRmDiTaV'}]}
             // 循环遍历,以memo_id为key,resource_name数组为value
             sourceRes["res"].forEach((item) => {
               if (this.resourceMap[item["memo_id"]]) {