Преглед изворни кода

token过期,自动申请token,自动尝试连接3次

panxingxin пре 5 година
родитељ
комит
705cab410a
4 измењених фајлова са 41 додато и 41 уклоњено
  1. 39 39
      api/request.js
  2. 1 0
      app.json
  3. 0 1
      pages/sample/list.json
  4. 1 1
      project.config.json

+ 39 - 39
api/request.js

@@ -2,12 +2,13 @@ const  Fly = require("../lib/wx.umd.min") //wx.js is your downloaded code
 const  fly = new Fly(); //Create an instance of Fly
 const app = getApp()
 
-//设置超时
 fly.config.timeout = 20000;
-
+fly.config.baseURL = "https://wx.sgsino.cn"
+const  newFly = new Fly(); 
+newFly.config = fly.config;
+let reqCount = 0 ;// 重发请求的次数
 // 获取白名单
 import whiteList from './whiteList';
-
 // Add interceptors
 fly.interceptors.request.use((request) => {
 // console.log('进入fly-request', request);
@@ -20,7 +21,7 @@ wx.showLoading({
     // 隐藏loading遮罩
     wx.hideLoading();
   }
-  // 请求资源服务器时,不添加token
+  // 白名单内url不添加token
   if (request.url.indexOf(whiteList.nullHeaderToken) !== -1) {
     request.timeout = 30000; // 请求超时
     request.headers = {
@@ -30,8 +31,7 @@ wx.showLoading({
     console.log('nullHeaderToken()')
     return request;
   }
-  // fly.lock()
-  // 延迟发请求 等 getStorageSync 存储
+  //头文件带Authorization为请求token,不添加token
   if (request.headers.Authorization) {
     // 给所有请求添加自定义header
     request.timeout = 30000;
@@ -39,10 +39,9 @@ wx.showLoading({
       'content-type': 'application/json',
       'X-Tag': 'flyio'
     })
-    // fly.unlock(); //解锁请求
     return request;
   }
-
+//其他请求需要在头文件中自动附加token
   if(wx.getStorageSync('token')) {
      // 给所有请求添加自定义header
      request.timeout = 30000;
@@ -51,50 +50,58 @@ wx.showLoading({
        'X-Tag': 'flyio',
        'Authorization': `Bearer ${wx.getStorageSync('token')}`
      })
-    //  fly.unlock(); //解锁请求
      return request;
   } 
-  //  else if(!wx.getStorageSync('token')&&app.getCurrentPages()=='pages/login/login') {
-  //   request.headers = {
-  //     'content-type': 'application/json',
-  //     'X-Tag': 'flyio',
-  //     'Authorization': 'Basic dGVzdDp0ZXN0'
-  //   };
-  //   fly.unlock();//解锁请求
-  //   return request;
-  // }
-  else {
-    console.log(app.getCurrentPages())
-  }
 }, (error, promise) => {
   // Do something with request error
   console.log(error); // for debug
   promise.reject(error)
 });
+
 fly.interceptors.response.use(
   (response) => {
+    //正常返回
+    reqCount =0;
     wx.hideLoading();
-    //只将请求结果的data字段返回
     return response
   },
   (err, promise) => {
     wx.hideLoading();
-    let msg = '';
+    let msg = ''; 
     if (err.status === 0) {
       msg = '网络连接异常'
-    } else if (err.status === 1) {
+    } 
+    else if (err.status === 1) {
       msg = '网络连接超时'
-    } else if (err.status === 401) {
-      msg = '用户未登录'
+    } 
+    else if (err.status === 401) {
+      reqCount += 1    
       wx.clearStorageSync('token')
-      // wx.navigateTo({
-      //   url: 'pages/me/me'
-      // });
-    } else {
+            if (reqCount < 3) {
+               msg = '用户已过期,正在自动刷新用户,尝试次数'+reqCount.toString();
+               this.lock(); //锁定响应拦截器
+               wx.login({ success(wxres)  {
+                  newFly.request(
+                    { url: '/auth/mobile/token/social?grant_type=mobil&mobile=MINI@'+ wxres.code,
+                     method: 'post',
+                     headers:{ 'Authorization': 'Basic dGVzdDp0ZXN0'}})
+                     .then(res => { if (res.data.access_token) {wx.setStorageSync('token', res.data.access_token); }})
+                     .finally(() => this.unlock())
+                     .then(() => { return fly.request(err.request); })}})
+    } 
+  }
+    else if (err.status === 502) {
+      reqCount += 1
+      if (reqCount < 3) {
+        msg = '网络错误,正在进行自动重试,重试次数'+reqCount.toString();
+         return fly.request(err.request);
+      }    
+    }       
+    else {
       if (err.response.data.message) {
         msg = err.response.data.message
       } else {
-        msg = '请求数据失败,请稍后再试'
+        msg = '程序已3次连接失败,请稍后手动登录后再试'
       }
     }
     wx.showToast({
@@ -102,16 +109,9 @@ fly.interceptors.response.use(
       icon: 'none',
       duration: 3000
     });
-    // setTimeout(() => {
-    //   console.log('fly.interceptors.err-toLogin')
-    //   wx.redirectTo({
-    //     url: '../login/login'
-    //   });
-    // }, 500)
     return promise.resolve(err)
   }
 )
-// Set the base url
-fly.config.baseURL = "https://wx.sgsino.cn"
+
 
 export default fly;

+ 1 - 0
app.json

@@ -32,6 +32,7 @@
     "backgroundTextStyle": "light",
     "navigationBarBackgroundColor": "#fff",
     "navigationBarTitleText": "WeChat",
+    "onReachBottomDistance": 50,
     "navigationBarTextStyle": "black"
   },
   "style": "v2",

+ 0 - 1
pages/sample/list.json

@@ -1,6 +1,5 @@
 {
   "usingComponents": {},
   "enablePullDownRefresh": true,
-  "onReachBottom": true,
   "navigationBarTitleText": "样品单列表"
 }

+ 1 - 1
project.config.json

@@ -15,7 +15,7 @@
 		"showShadowRootInWxmlPanel": true,
 		"scopeDataCheck": false,
 		"checkInvalidKey": true,
-		"checkSiteMap": true,
+		"checkSiteMap": false,
 		"uploadWithSourceMap": true,
 		"babelSetting": {
 			"ignore": [],