Browse Source

update: add request.js and update utils.js

Notobey 4 years ago
parent
commit
3a9cc47409
10 changed files with 237 additions and 110 deletions
  1. 11 0
      api/index.js
  2. 2 2
      app.js
  3. 26 18
      pages/collection/collection.js
  4. 12 19
      pages/index/bangdan/bangdan.js
  5. 18 26
      pages/index/index.js
  6. 8 2
      pages/index/index.wxml
  7. 22 12
      pages/user/user.js
  8. 7 2
      project.config.json
  9. 36 0
      utils/request.js
  10. 95 29
      utils/utils.js

+ 11 - 0
api/index.js

@@ -0,0 +1,11 @@
+const request = require('../utils/request').request;
+
+function getData() {
+  return request({
+    method: 'get'
+  })
+}
+
+module.exports = {
+  getData
+}

+ 2 - 2
app.js

@@ -9,7 +9,7 @@ App({
           wx.getUserInfo({
             success: res => {
               // 可以将 res 发送给后台解码出 unionId
-              console.log("app.js:"+res.userInfo)
+              // console.log("app.js:"+res.userInfo)
               this.globalData.userInfo = res.userInfo
               this.globalData.login = false
               // 由于 getUserInfo 是网络请求,可能会在 Page.onLoad 之后才返回
@@ -24,6 +24,6 @@ App({
     })
   },
   globalData: {
-    userInfo: null
+    userInfo:null
   }
 })

+ 26 - 18
pages/collection/collection.js

@@ -1,7 +1,6 @@
 // pages/collection/collection.js
 const app = getApp()
-let userInfo = app.globalData.userInfo;
-let height = app.globalData.phoneHeight
+
 Page({
 
   /**
@@ -9,13 +8,14 @@ Page({
    */
   data: {
     currentIndex:0,
-    height:height,
+    height:0,
     content: [
       {text: "我的收藏"},
       {text: "我的已购"},
       {text: "收听历史"},
       {text: "我的礼包"}
-    ]
+    ],
+    login: true
   },
 
   /**
@@ -23,23 +23,27 @@ Page({
    */
   onLoad: function (options) {
     var that = this;
-    var height;
     wx.getSystemInfo({
       success (res) {
-        console.log(res.windowHeight);
-        height = res.windowHeight
+        that.setData({
+          height :res.windowHeight
+        })
       }
     })
-    if (app.globalData.userInfo === null){
-      that.setData({
-        login:true
-      })
-    }else{
-      that.setData({
-        login: false,
-        height:height
-      })
-    }
+    wx.getStorage({
+      key: 'login',
+      success(res){
+        if(res.data === 200){
+          that.setData({
+            login: false,
+          })
+        }
+      },
+      fail(res){
+        console.log(res)
+      }
+    })
+
   },
 
 
@@ -56,13 +60,17 @@ Page({
     wx.getUserInfo({
       success: function (res) {
         app.globalData.userInfo = e.detail.userInfo;
-        console.log(e.detail.userInfo);
+        wx.setStorage({
+          key: "login",
+          data: 200
+        })
         that.setData({
           login: false,
         })
       }
     })
   },
+
   checkItem(e){
     var that = this;
     if (this.data.currentIndex === e.target.dataset.current) {

+ 12 - 19
pages/index/bangdan/bangdan.js

@@ -1,7 +1,7 @@
 const app = getApp();
-var utils = require('../../../utils/utils.js')
+let myRequest = require('../../../api/index.js')
 // 定义一个全局变量保存从接口获取到的数据,以免重复请求接口
-var resut; 
+let resut; 
 Page({
 
   /**
@@ -26,21 +26,14 @@ Page({
    * 生命周期函数--监听页面加载
    */
   onLoad: function (options) {
-    var that = this;
-    var url = 'http://mobile.ximalaya.com/mobile/discovery/v3/recommend/hotAndGuess?code=43_310000_3100&device=android&version=5.4.45'
-    utils.myRequest({
-      url:url,
-      methods:'GET',
-      success:function(res){
-        console.log(res);
-        resut = res;
-        that.setData({
-          list: res.data.hotRecommends.list[0].list
-        })
-      },
-      fail:function(){
-
-      }
+    let that = this;
+    myRequest.getData().then(res => {
+      resut = res;
+      that.setData({
+        list: res.data.hotRecommends.list[0].list
+      })
+    }).catch(err => {
+      console.log(err);
     })
   },
   handleClick(e) {
@@ -52,13 +45,13 @@ Page({
     })
   },
   pullDown:function(){
-    var that = this;
+    let that = this;
     that.setData({
       showCover:true
     })
   },
   closeCover:function(){
-    var that = this;
+    let that = this;
     that.setData({
       showCover:false
     })

+ 18 - 26
pages/index/index.js

@@ -1,10 +1,8 @@
 //index.js
 //获取应用实例
 const app = getApp()
-var utils = require('../../utils/utils.js');
-
+const myRequest = require('../../api/index.js');
 Page({
-
   /**
    * 页面的初始数据
    */
@@ -42,33 +40,26 @@ Page({
     ],
     swiperCurrent: 0,
   },
-
   /**
    * 生命周期函数--监听页面加载
    */
   onLoad: function (options) {
-    var that = this;
-    var url = 'http://mobile.ximalaya.com/mobile/discovery/v3/recommend/hotAndGuess?code=43_310000_3100&device=android&version=5.4.45';
-
-    // 调用的是自己封装的工具函数,在utils中
-    utils.myRequest({
-      url: url,
-      methods: 'GET',
-      success: function (result) {
-        that.setData({
-          showitem: true,
-          guess: result.data.paidArea.list,
-          xiaoshuocontent: result.data.hotRecommends.list[0].list,
-          xiangshengcontent: result.data.hotRecommends.list[2].list,
-          tuokocontent: result.data.hotRecommends.list[4].list
-        })
-      },
-      fail: function () {
-        that.setData({
-          showitem: false
-        })
-      }
-    });
+    var that = this
+    myRequest.getData().then(res => {
+      console.log('res',res);
+      that.setData({
+        showitem: true,
+        guess: res.data.guess.list.slice(0,3),
+        xiaoshuocontent: res.data.hotRecommends.list[0].list,
+        xiangshengcontent: res.data.hotRecommends.list[2].list,
+        tuokocontent: res.data.hotRecommends.list[4].list
+      })
+    }).catch(err => {
+      console.log(err);
+      that.setData({
+        showitem: false
+      })
+    })
   },
   //轮播图改变事件
   swiperChange: function (e) {
@@ -85,6 +76,7 @@ Page({
     var url = e.currentTarget.dataset.coverimg;
     var title = e.currentTarget.dataset.title;
     wx.navigateTo({
+      // 页面传参
       url: '/pages/details/details?url=' + url + '&title=' + title,
     })
   }

+ 8 - 2
pages/index/index.wxml

@@ -43,9 +43,15 @@
     <view class="hmly-title-left">猜你喜欢</view>
     <view class="hmly-title-right">查看全部 <text class="icon-right"></text> </view>
   </view>
-  <!-- 这没有没有使用数据绑定,因为是练手而且数据比较少 -->
+  <!-- 这没有使用数据绑定,因为是练手而且数据比较少 -->
   <view class="hmly-like-item-box">
-    <view class="hmly-like-item" bindtap="gotoDetails" data-coverImg="{{item.coverMiddle}}" data-title="{{item.intro}}" wx:for="{{guess}}" wx:key="{{index}}">
+    <view class="hmly-like-item"
+      bindtap="gotoDetails"
+      data-coverImg="{{item.coverMiddle}}"
+      data-title="{{item.intro}}"
+      wx:for="{{guess}}"
+      wx:key="{{index}}"
+    >
       <view class="hmly-like-img">
         <image class="hmly-like-item-icon" src="{{item.coverMiddle}}" mode="widthFix"></image>
         <view class="hmly-like-cover">

+ 22 - 12
pages/user/user.js

@@ -18,6 +18,9 @@ Page({
       {text:"30分钟后"},
     ],
     activeIndex:0,
+    login: true,
+    avatarUrl:"",
+    nickName:""
   },
 
   onLoad: function (options) {
@@ -32,25 +35,32 @@ Page({
       }
     })
     // 查看是否授权
-    if (app.globalData.userInfo === null) {
-      that.setData({
-        login: true
-      })
-    } else {
-      that.setData({
-        login: false,
-        avatarUrl: app.globalData.userInfo.avatarUrl,
-        nickName: app.globalData.userInfo.nickName
-      })
-    }
+    wx.getStorage({
+      key: 'login',
+      success(res){
+        if (res.data === 200) {
+          that.setData({
+            login: false
+          })
+        } else {
+          that.setData({
+            login: true
+          })
+        }
+      }
+    })
+    
   },
   // 获取用户的头像和昵称信息
   bindGetUserInfo(e) {
     var that = this;
     wx.getUserInfo({
       success: function(res) {
-        console.log(e.detail.userInfo);
         app.globalData.userInfo = e.detail.userInfo;
+        wx.setStorage({
+          key: "login",
+          data: 200
+        })
         that.setData({
           login: false,
           avatarUrl: e.detail.userInfo.avatarUrl,

+ 7 - 2
project.config.json

@@ -7,10 +7,13 @@
 		"urlCheck": false,
 		"es6": true,
 		"postcss": true,
+		"preloadBackgroundData": false,
 		"minified": true,
 		"newFeature": true,
 		"coverView": true,
 		"autoAudits": false,
+		"showShadowRootInWxmlPanel": true,
+		"scopeDataCheck": false,
 		"checkInvalidKey": true,
 		"checkSiteMap": true,
 		"uploadWithSourceMap": true,
@@ -18,10 +21,12 @@
 			"ignore": [],
 			"disablePlugins": [],
 			"outputPath": ""
-		}
+		},
+		"useCompilerModule": false,
+		"userConfirmedUseCompilerModuleSwitch": false
 	},
 	"compileType": "miniprogram",
-	"libVersion": "2.10.3",
+	"libVersion": "2.11.3",
 	"appid": "wx101d03d3f1aab84c",
 	"projectname": "%E4%BB%BF%E5%96%9C%E9%A9%AC%E6%8B%89%E9%9B%85lite",
 	"debugOptions": {

+ 36 - 0
utils/request.js

@@ -0,0 +1,36 @@
+// 定义全局常量baseUrl用来存储前缀
+const baseURL = 'http://mobile.ximalaya.com/mobile/discovery/v3/recommend/hotAndGuess?code=43_310000_3100&device=android&version=5.4.45';
+
+function request(params = {method, url, data}) {
+  return new Promise(function (resolve, reject) {
+    let header = {    //定义请求头
+      'content-type': 'application/json',
+    };
+    wx.request({
+      url: baseURL + params.url,
+      method: params.method,
+      data: params.data ? JSON.stringify(params.data) : null,
+      header: header,
+      success(res) {
+        //请求成功
+        //判断状态码---errCode状态根据后端定义来判断
+        if (res.data.code != '-1') {  //请求成功
+          resolve(res);
+        } else {
+          //其他异常
+          reject('运行时错误,请稍后再试');
+        }
+      },
+      fail(err) {
+        //请求失败
+        reject(err)
+      }
+    })
+  })
+}
+
+
+// 向外暴露接口
+module.exports = {
+  request : request
+}

+ 95 - 29
utils/utils.js

@@ -1,35 +1,101 @@
 /**
- * 本文件主要是工具类函数
- */
-
-
- /*
-  自己基于wx.request封装的一个请求函数(粗陋封装各位不要笑话)
-  因为在小程序开发中request是最常用的api所以会造成很多的代码重复
-  因此将其在封装之后可以大大的减少代码的复用
-*/
-let myRequest = function(args = {url:'',methods:'GET', data:{}, success:function(){},fail:function(){}}){
-    wx.request({
-        url: args.url,
-        data: args.data,
-        header: {'content-type':'application/json'},
-        method: args.methods,
-        dataType: 'json',
-        responseType: 'text',
-        success: (res)=>{
-          console.log(res);
-          if(res.statusCode == 200){
-            // 请求成功执行回调函数
-            args.success(res)
-          }else{
-            // 请求失败执行回调函数
-            args.fail()
-          }
-        },
-    })
+ * Created by PanJiaChen on 16/11/18.
+ * 避免重复造轮子,这里照搬花裤衩大佬的代码使用
+ */
+
+/**
+ * @param {string} path
+ * @returns {Boolean}
+ */
+function isExternal(path) {
+  return /^(https?:|mailto:|tel:)/.test(path)
+}
+
+/**
+ * @param {string} str
+ * @returns {Boolean}
+ */
+function validUsername(str) {
+  const valid_map = ['admin', 'editor']
+  return valid_map.indexOf(str.trim()) >= 0
+}
+
+/**
+ * @param {string} url
+ * @returns {Boolean}
+ */
+function validURL(url) {
+  const reg = /^(https?|ftp):\/\/([a-zA-Z0-9.-]+(:[a-zA-Z0-9.&%$-]+)*@)*((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9][0-9]?)(\.(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])){3}|([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+\.(com|edu|gov|int|mil|net|org|biz|arpa|info|name|pro|aero|coop|museum|[a-zA-Z]{2}))(:[0-9]+)*(\/($|[a-zA-Z0-9.,?'\\+&%$#=~_-]+))*$/
+  return reg.test(url)
+}
+
+/**
+ * @param {string} str
+ * @returns {Boolean}
+ */
+function validLowerCase(str) {
+  const reg = /^[a-z]+$/
+  return reg.test(str)
+}
+
+/**
+ * @param {string} str
+ * @returns {Boolean}
+ */
+function validUpperCase(str) {
+  const reg = /^[A-Z]+$/
+  return reg.test(str)
+}
+
+/**
+ * @param {string} str
+ * @returns {Boolean}
+ */
+function validAlphabets(str) {
+  const reg = /^[A-Za-z]+$/
+  return reg.test(str)
+}
+
+/**
+ * @param {string} email
+ * @returns {Boolean}
+ */
+function validEmail(email) {
+  const reg = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/
+  return reg.test(email)
+}
+
+/**
+ * @param {string} str
+ * @returns {Boolean}
+ */
+function isString(str) {
+  if (typeof str === 'string' || str instanceof String) {
+    return true
+  }
+  return false
+}
+
+/**
+ * @param {Array} arg
+ * @returns {Boolean}
+ */
+function isArray(arg) {
+  if (typeof Array.isArray === 'undefined') {
+    return Object.prototype.toString.call(arg) === '[object Array]'
+  }
+  return Array.isArray(arg)
 }
 
 // 向外暴露接口
 module.exports = {
-  myRequest : myRequest
+  isExternal,
+  validUsername,
+  validURL,
+  validLowerCase,
+  validUpperCase,
+  validAlphabets,
+  validEmail,
+  isString,
+  isArray
 }