微信小程序框架封装登录,网络请求等公共模块及调用示例

这个公共模块封装了session的获取,和fromId发送,showToast成功和失败的弹窗。
微信小程序公共通用模块

const util = require('../utils/util.js');
 
function init() {
  var that = this;
  // session定时器
  that.sessionIsExpire = (resolve) => {
    const session = wx.getStorageSync('session');
    const deadLine = wx.getStorageSync('deadline');
    const nowDate = new Date().getTime();
    if (session && deadLine) {
      if (nowDate - deadLine >= 1000 * 60 * 60 * 24) {
        that.login(resolve)
      } else {
        wx.checkSession({
          success() {
            // session_key 未过期,并且在本生命周期一直有效
            resolve(session)
          },
          fail() {
            // session_key 已经失效,需要重新执行登录流程
            that.login(resolve)
          }
        })
      }
    } else {
      that.login(resolve)
    }
  }
  // wx.login
  that.login = (resolve) => {
    wx.login({
      success: (res) => {
        if (res.code) {
          that.loginRequest(res.code, resolve);
        }
      },
    })
  }
  // 请求login.do接口得到session
  that.loginRequest = (code, resolve) => {
    var url = '/v1/user/login.do';
    var data = {
      code,
      minipId: 'worder'
    };
    util.request(url, 'post', data,'', (res) => {
      console.log('登录了')
      if (res.data.success == true) {
        const session = res.data.module.session;
        resolve(session)
        wx.setStorageSync('session', session);
        wx.setStorageSync('deadline', new Date().getTime())
      } else {
        resolve(1)
      }
    }, (fail) => {
      resolve(1)
    })
  }
  // 获取session
  that.pro_getSession = new Promise((resolve) => {
    that.sessionIsExpire(resolve)
  })
  // 成功的提示
  that.showToast_scss = (e) => {
    wx.showToast({
      title: e
    })
  }
  // 失败的提示
  that.showToast_fail = (e) => {
    wx.showToast({
      title: e,
      icon: 'none'
    })
  }
  // 跳转小程序
  that.to_rel = (appId,path,extraData='') => {
    console.log('跳转小程序')
    wx.navigateToMiniProgram({
      appId,
      path,
      extraData,
      envVersion: 'release',
      success(res) {
        // 打开成功
      }
    })
  }
  //获取formid
  that.formSubmit = function(e) {
    var date = Date.parse(new Date());
    var if_date = wx.getStorageSync('formId_time')
    if ((date - if_date) > 1000 * 3) {
      wx.setStorageSync('formId_time', date);
      if (e && e.detail && e.detail.formId) {
        let data = {
          session: wx.getStorageSync("session"),
          formId: e.detail.formId,
          btnName: 'btn'
        };
        util.request('/v1/customermanager/saveFormid.do', 'post', data, '', (res) => {
          wx.setStorageSync('formId_time', new Date())
        });
      }
    }
  }
}
module.exports = {
  init: init
}
调用方式

 
const util = require('../../utils/util.js');
var common = require('../common.js');  
Page({
   /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    common.init.apply(this, []); //导入公共js
    
    //需要使用session时写法示例
    this.pro_getSession.then(resolve => {
        var session = resolve ;
    })
 
    //需要使用自定义弹窗时写法示例
    this.showToast_fail(res.data.errorMsg)
  })
})
util.js 封装的代码

const formatTime = date => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()
 
  return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}
// 网络请求
const request = function(url, method, data, msg, succ, fail, com) {
  // 小程序顶部显示Loading
  wx.showNavigationBarLoading();
  if (msg != "") {
    wx.showLoading({
      title: msg
    })
  }
  wx.request({
    url: 'https://***.cn'+url,
    data: data,
    header: {
      'content-type': 'application/x-www-form-urlencoded'
    },
    method: method,
    success: res => {
      if (succ) succ(res);
    },
    fail: err => {
      wx.showToast({
        title: '网络错误,请稍后再试···',
        icon:'none'
      })
      if (fail) fail(err);
    },
    complete: com => {
      wx.hideNavigationBarLoading();
      if (msg != "") {
        wx.hideLoading();
      }
      console.log(url + ' 返回的data:', com.data);
    }
  })
}
const formatNumber = n => {
  n = n.toString()
  return n[1] ? n : '0' + n
}
 
module.exports = {
  formatTime: formatTime,
  request: request
}
 


--------------------- 
作者:a_靖 
来源:CSDN 
原文:https://a-jing.blog.csdn.net/article/details/89313330 
版权声明:本文为博主原创文章,转载请附上博文链接!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值