XiaBx 3 anni fa
parent
commit
ad646d0620

+ 3 - 3
src/App.vue

@@ -31,7 +31,7 @@
 </template>
 
 <script>
-
+import {uuidsGetTokens} from "./api";
 export default {
   name: "app",
   data() {
@@ -54,7 +54,7 @@ export default {
       }
     }
   },
-  created() {
+  async created() {
     
     let { site_gender } = window.options;
     if (site_gender) {
@@ -75,7 +75,7 @@ export default {
       "BookLimitFree",
       "Yun"
     ];
-
+    console.log(11111111111111111)
     //获取是否加桌过
     const { is_add_desk } = window.options;
     if (

+ 30 - 21
src/api/axios.js

@@ -3,6 +3,7 @@ import router from "../router/index.js";
 import { Undertheshelf } from "../view/namespace.js";
 import { undefinedCollect } from "./index.js";
 import { getToken, refreshToken } from "./config";
+import { addPendingRequest, removePendingRequest } from "./cancelRepeatRquest";
 import { Toast } from "mint-ui";
 // var instance = axios.create(
 //   process.env.NODE_ENV === "development"
@@ -14,35 +15,43 @@ import { Toast } from "mint-ui";
 //         baseURL: "/api"
 //       }
 // );
-const whiteList = ["/login"];
+const whiteList = ["/login", "/hashuserToToken"];
 
 var instance = axios.create({
   baseURL: "/api"
 });
 
-instance.interceptors.response.use(async function(res) {
-  if (res.data.code === 0) {
-    return res.data.data;
+instance.interceptors.response.use(
+  async res => {
+    if (res.data.code === 0) {
+      //removePendingRequest(res);
+      return res.data.data;
+    }
+    if (
+      res.data.code === 10001 ||
+      res.data.code === 10023 ||
+      res.data.code === 10035
+    ) {
+      Toast("重新登录中");
+      await refreshToken();
+      return axios(res.config);
+    }
+    if (res.data.code === 10018) {
+      router.replace(Undertheshelf.route);
+    } else {
+      return Promise.reject(res);
+    }
+  },
+  error => {
+    //removePendingRequest(error.config || {});
+    return Promise.reject(error);
   }
-  if (
-    res.data.code === 10001 ||
-    res.data.code === 10023 ||
-    res.data.code === 10035
-  ) {
-    Toast("重新登录中");
-    await refreshToken();
-    return axios(res.config);
-  }
-  if (res.data.code === 10018) {
-    router.replace(Undertheshelf.route);
-  } else {
-    return Promise.reject(res);
-  }
-});
+);
 instance.interceptors.request.use(async function(config) {
   let token = localStorage.getItem("token");
-  
+
   if (!whiteList.includes(config.url) && !token) {
+    console.log(config.url);
     token = await getToken(config);
   }
   if (token) {
@@ -65,7 +74,7 @@ instance.interceptors.request.use(async function(config) {
       })
     });
   }
-
+  //addPendingRequest(config);
   return config;
 });
 

+ 39 - 0
src/api/cancelRepeatRquest.js

@@ -0,0 +1,39 @@
+// 取消重复请求
+/*  假如用户重复点击按钮,先后提交了 A 和 B 这两个完全相同(考虑请求路径、方法、参数)的请求:
+    只发第一个请求。在 A 请求还处于 pending 状态时,后发的所有与 A 重复的请求都取消,实际只发出 A 请求,直到 A 请求结束(成功/失败)才停止对这个请求的拦截。
+*/
+import Axios from "axios";
+import { generateReqKey } from "./config";
+
+// addPendingRequest :用于把当前请求信息添加到pendingRequest对象 中;
+const pendingRequest = new Map(); // Map对象保存键值对。任何值(对象或者原始值) 都可以作为一个键或一个值。
+export function addPendingRequest(config) {
+  if (config.cancelRequest) {
+    const requestKey = generateReqKey(config);
+    if (pendingRequest.has(requestKey)) {
+      config.cancelToken = new Axios.CancelToken(cancel => {
+        // cancel 函数的参数会作为 promise 的 error 被捕获
+        cancel(`${config.url} 请求已取消`);
+      });
+    } else {
+      config.cancelToken =
+        config.cancelToken ||
+        new Axios.CancelToken(cancel => {
+          pendingRequest.set(requestKey, cancel);
+        });
+    }
+  }
+}
+
+// removePendingRequest:检查是否存在重复请求,若存在则取消已发的请求。
+export function removePendingRequest(response) {
+  if (response && response.config && response.config.cancelRequest) {
+    const requestKey = generateReqKey(response.config);
+    // 判断是否有这个 key
+    if (pendingRequest.has(requestKey)) {
+      const cancelToken = pendingRequest.get(requestKey);
+      cancelToken(requestKey);
+      pendingRequest.delete(requestKey);
+    }
+  }
+}

+ 30 - 5
src/api/config.js

@@ -1,13 +1,12 @@
 import { userLogin } from "./index";
+import Qs from "qs";
 
 export async function getToken(config) {
-  return  login();
+  return login();
 }
 
-
 export async function login() {
   console.log("我还在登录中");
-  const signKey = "a!A&AFRWT65Nb3NlklezUiqHyQAA@Z8M";
   const timestamp = parseInt(new Date().valueOf() / 1000);
   let data = {
     timestamp
@@ -15,14 +14,40 @@ export async function login() {
   let ret = await userLogin(data);
   if (ret) {
     localStorage.setItem("token", ret.token);
+    localStorage.setItem("uuids", ret.hashuser);
     return Promise.resolve(ret.token);
   } else {
     return Promise.reject("false");
   }
 }
 
-
 export async function refreshToken() {
   localStorage.removeItem("token");
   await getToken();
-}
+}
+
+export function generateReqKey(config) {
+  // 响应的时候,response.config 中的data 是一个JSON字符串,所以需要转换一下
+  if (config && config.data && isJsonStr(config.data)) {
+    config.data = JSON.parse(config.data);
+  }
+  const { method, url, params, data } = config; // 请求方式,参数,请求地址,
+  return [method, url, Qs.stringify(params), Qs.stringify(data)].join("&"); // 拼接
+}
+
+// 判断一个字符串是否为JSON字符串
+export let isJsonStr = str => {
+  if (typeof str == "string") {
+    try {
+      var obj = JSON.parse(str);
+      if (typeof obj == "object" && obj) {
+        return true;
+      } else {
+        return false;
+      }
+    } catch (e) {
+      console.log("error:" + str + "!!!" + e);
+      return false;
+    }
+  }
+};

+ 6 - 1
src/api/index.js

@@ -623,5 +623,10 @@ export function getYun(id){
 
 //获取最近阅读记录
 export function getRecentReader(){
-  return axios(`readrecord/getLastRead`,);
+  return axios(`/readrecord/getLastRead`,);
+}
+
+//换取userId
+export function uuidsGetTokens(uuid){
+  return axios(`/hashuserToToken`,{params:{hashuser:uuid}})
 }

+ 13 - 4
src/router/index.js

@@ -1,7 +1,7 @@
 import Vue from "vue";
 import Router from "vue-router";
 import * as namespace from "../view/namespace.js";
-
+import { uuidsGetTokens } from "../api/index";
 // import BookCity from '../view/book-city.vue'
 // import BookStock from '../view/book-stock.vue'
 // import BookShelf from '../view/book-shelf.vue'
@@ -133,15 +133,24 @@ const router = new Router({
   }
 });
 
-router.beforeEach((to, from, next) => {
+router.beforeEach(async (to, from, next) => {
   window.prevPage = from.fullPath;
   //alert('即将前往'+document.domain+to.fullPath);
   window.nextPage = to.fullPath;
   window.nextName = to.name;
-  if (!window.firstName) window.firstName = to.name;
+
+  if (!window.firstName) {
+    window.firstName = to.name;
+    const token = localStorage.getItem("token");
+    const uuids = localStorage.getItem("uuids") || to.query.uuids;
+    if (uuids && !token) {
+      let source = await uuidsGetTokens(uuids);
+      if (source.token ) localStorage.setItem("token", source.token);
+    }
+  }
   to.meta ? (to.meta.behavior = behavior) : (to.meta = { behavior });
   behavior = "user";
- next();
+  next();
 });
 
 router.afterEach(function(router, from) {

+ 6 - 0
src/view/book-catalog.vue

@@ -95,6 +95,7 @@ export default {
           defaultIndex: 0,
         },
       ],
+      uuids:'',
       meta: {},
       tempPage: 1,
       handler: function (e) {
@@ -204,6 +205,7 @@ export default {
             chapter_id: cid,
             fee: chapter_cost,
             code: 10021,
+            uuids:this.uuids
           },
         });
       } else {
@@ -212,6 +214,7 @@ export default {
           query: {
             bid,
             cid,
+            uuids:this.uuids
           },
         });
       }
@@ -231,6 +234,9 @@ export default {
   },
   created() {
     if (catalog) {
+      let uuid = localStorage.getItem("uuids");
+      let {uuids } = this.$route.query;
+      this.uuids = uuids || uuid;
       this.catalogs = catalog.data;
       this.meta = catalog.meta;
       if (this.catalogs.length > catalog.meta.per_page) {

+ 9 - 4
src/view/book-detail.vue

@@ -55,7 +55,7 @@
     <router-link
       :to="{
         name: Reader.name,
-        query: { bid: book.book_id, cid: book.last_cid }
+        query: { bid: book.book_id, cid: book.last_cid } 
       }"
       tag="div"
       class="book-detail-lastest"
@@ -124,7 +124,8 @@ export default {
       count: 0,
       prevTime: 0,
       endTime: 0,
-      showDebug: false
+      showDebug: false,
+      uuids:''
     };
   },
   methods: {
@@ -141,7 +142,8 @@ export default {
         name: Reader.name,
         query: {
           bid: this.book.book_id,
-          cid: cid
+          cid: cid,
+          uuids:this.uuids
         }
       });
     },
@@ -185,6 +187,9 @@ export default {
   },
   created() {
     this.init();
+    let uuid = localStorage.getItem("uuids");
+    let {uuids } = this.$route.query;
+    this.uuids = uuids || uuid;
   },
   beforeRouteUpdate(to, from, next) {
     getDetail(to.query.id, "detail")
@@ -203,7 +208,7 @@ export default {
       pos = to.params.pos;
     }
     let id = to.query.id;
-    if (!id) next({ path: "/", replace: true });
+    if (!id) next({ path: "/", replace: true,query:{uuids:this.uuids} });
     getDetail(id, "detail", pos)
       .catch(e => {
         let replace_url = e.data.data.url + location.pathname + location.search;

+ 6 - 1
src/view/book-recent.vue

@@ -121,6 +121,7 @@ export default {
       hideBookName: !!window.options.hide_book_name,
       showFreeEntry: window.options.guidepersonalaccount,
       activity_link: window.options.activity_link,
+      uuids:'',
     };
   },
   methods: {
@@ -161,6 +162,7 @@ export default {
         query: {
           bid: book.bid,
           cid: book.cid,
+          uuids:this.uuids
         },
       });
     },
@@ -196,7 +198,7 @@ export default {
         this.ClickStatistics(book.book_id);
         this.$router.push({
           name: BookDetail.name,
-          query: { id: book.book_id },
+          query: { id: book.book_id,uuids:this.uuids },
           params:{pos:'recent_banner'}
         });
       }
@@ -208,6 +210,9 @@ export default {
       this.books = r;
       this.getRecentSwiperList();
     });
+    let uuid = localStorage.getItem("uuids");
+      let {uuids } = this.$route.query;
+      this.uuids = uuids || uuid;
   },
 };
 </script>

+ 8 - 3
src/view/book-shelf.vue

@@ -42,7 +42,8 @@ export default {
     return {
       BookRecent: BookRecent.route,
       books: [],
-      edit: false
+      edit: false,
+      uuids:""
     };
   },
   methods: {
@@ -51,7 +52,8 @@ export default {
         name: Reader.name,
         query: {
           bid: book.bid,
-          cid: book.last_cid
+          cid: book.last_cid,
+          uuids:this.uuids
         }
       });
     },
@@ -61,7 +63,7 @@ export default {
       });
     },
     addBook() {
-      this.$router.push(BookCity.route);
+      this.$router.push({name:BookCity.route, query: {uuids:this.uuids }});
     },
     editChange() {
       this.edit = !this.edit;
@@ -71,6 +73,9 @@ export default {
     getShelf().then(r => {
       this.books = r;
     });
+    let uuid = localStorage.getItem("uuids");
+      let {uuids } = this.$route.query;
+      this.uuids = uuids || uuid;
   }
 };
 </script>

+ 7 - 3
src/view/person.vue

@@ -42,14 +42,14 @@
         </div>
       </router-link>
       <div style="height: 0.2rem;background-color: #F5F5F5;"></div>
-      <router-link class="person-entry__shelf" :to="Coupon" tag="div">
+      <router-link class="person-entry__shelf" :to="{name:Coupon.name,query:{uuids}}" tag="div">
         <img class="person-entry__icon" src="../assets/my_coupon.png" />
         <span class="person-entry__text">我的优惠券</span>
         <img class="person-entry__arrow" src="../assets/个人中心-进入.png" />
       </router-link>
 
       <hr />
-      <router-link class="person-entry__shelf" :to="BookRecent" tag="div">
+      <router-link class="person-entry__shelf" :to="{name:BookRecent.name,query:{uuids}}" tag="div">
         <img class="person-entry__icon" src="../assets/个人中心-书架.png" />
         <span class="person-entry__text">我的书架</span>
         <img class="person-entry__arrow" src="../assets/个人中心-进入.png" />
@@ -61,7 +61,7 @@
         <img class="person-entry__arrow" src="../assets/个人中心-进入.png" />
       </router-link>
       <hr />
-      <router-link tag="div" :to="RecordOrder" class="person-entry__order">
+      <router-link tag="div" :to="RecordOrder"  class="person-entry__order">
         <img class="person-entry__icon" src="../assets/个人中心-消费记录.png" />
         <span class="person-entry__text">消费记录</span>
         <img class="person-entry__arrow" src="../assets/个人中心-进入.png" />
@@ -119,6 +119,7 @@ export default {
       Coupon: Coupon.route,
       Login: Login.route,
       user: {},
+      uuids:''
     };
   },
   methods: {
@@ -158,6 +159,9 @@ export default {
     getUserInfo().then(r => {
       this.user = r;
     });
+    let uuid = localStorage.getItem("uuids");
+      let {uuids } = this.$route.query;
+      this.uuids = uuids || uuid;
   }
 };
 </script>

+ 8 - 9
src/view/reader.vue

@@ -363,13 +363,13 @@ export default {
             query: {
               bid: this.text.bid,
               cid: this.text.next_cid,
-              uuids:this.uuids
+              uuids: this.uuids
             }
           });
         } else if (this.text.next_cid === 0) {
           this.$router.push({
             name: BookRecommend.name,
-            query: { bid: this.$route.query.bid,uuids:this.uuids }
+            query: { bid: this.$route.query.bid, uuids: this.uuids }
           });
         } else {
           this.$Toast("系统错误");
@@ -383,7 +383,7 @@ export default {
           query: {
             bid: this.text.bid,
             cid: this.text.prev_cid,
-            uuids:this.uuids
+            uuids: this.uuids
           },
           params: {
             jump: -1
@@ -419,7 +419,7 @@ export default {
           query: {
             bid: bid,
             cid: cid,
-            uuids:this.uuids
+            uuids: this.uuids
           }
         });
       }
@@ -645,7 +645,7 @@ export default {
     },
     justifyRouter(router) {
       if (!router.query.bid) {
-        this.$router.replace({path:'/',query:{uuids:this.uuids}});
+        this.$router.replace({ path: "/", query: { uuids: this.uuids } });
         return false;
       }
       if (typeof router.query.bid !== "string") {
@@ -654,7 +654,7 @@ export default {
           query: {
             bid: router.query.bid[0],
             cid: router.query.cid,
-            uuids:this.uuids
+            uuids: this.uuids
           }
         });
         return false;
@@ -664,7 +664,7 @@ export default {
           query: {
             bid: router.query.bid.split(",")[0],
             cid: router.query.cid,
-            uuids:this.uuids
+            uuids: this.uuids
           }
         });
         return false;
@@ -710,8 +710,7 @@ export default {
       window.navigator.standalone
     ) {
       let sare = await getRecentReader();
-      if (sare.bid && sare.bid != bid && sare.cid != cid) {
-
+      if (sare.bid && sare.cid != cid) {
         this.$router.replace(
           `/reader?bid=${sare.bid}&cid=${sare.cid}&yun=${yun}&uuids=${this.uuids}`
         );