当前位置: 首页 > 编程日记 > 正文

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

微信小程序开发交流qq群   173683895

   承接微信小程序开发。扫码加微信。

这个公共模块封装了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.loginthat.login = (resolve) => {wx.login({success: (res) => {if (res.code) {that.loginRequest(res.code, resolve);}},})}// 请求login.do接口得到sessionthat.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)})}// 获取sessionthat.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) {// 打开成功}})}//获取formidthat.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() + 1const 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) {// 小程序顶部显示Loadingwx.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
}

相关文章:

安装centos后无法引导启动windows7的解决方法

在电脑Windows7系统上安装Centos7,安装后找不到Windows7引导菜单。 原因:因为CentOS 7已采用新式的grub2系统,所以需要进入/boot/grub2目录后使用vi编辑grub.cfg文件。 解决方法一:修改Centos 7的Grub2引导,添加Window…

git最佳实践_Git最佳实践如何为我节省大量的返工时间

git最佳实践by Hemal Patel通过赫马尔帕特尔 Git最佳实践如何为我节省大量的返工时间 (How Git best practices saved me hours of rework) Recently I was working on the task to upgrade a certificate for a NodeJS application. This was last touched two years ago for…

商品列表选择尺寸和颜色高亮,并且把选择的数据传递到下一个页面

微信小程序开发交流qq群 173683895 承接微信小程序开发。扫码加微信。 需求:商品列表选择属性,给中的属性显示高亮,并且把选择的数据记录下来传递到下一个页面。 项目下载地址:点击去下载 效果图: 选择商品的属性…

Android studio 使用心得(三)—从Eclipse迁移到Android studio

断断续续的也算是把eclipse上的代码成功迁移到android studio上来了,现在,我同事继续用eclipse,我用android studio,svn上还是之前eclipse的项目,迁移成功后,我也能happy的开发了,两不误.直接来分享我捉摸的…

代码改变世界_改变世界,一次只写一行代码

代码改变世界People like to look at changing the world as a big task. I believe changing the world can be done in little steps.人们喜欢将改变世界视为一项艰巨的任务。 我相信,改变世界可以一步步完成。 The key is identifying a problem and taking a l…

14_传智播客iOS视频教程_instancetype

12312312转载于:https://www.cnblogs.com/ZHONGZHENHUA/p/7097094.html

HDU 1011-Starship Troopers(树形背包)

题意: 有n个洞,连接像一棵树,每个包含一定数量的怪和价值,给你m个士兵,每个士兵能打20个怪,杀完一个洞的怪可得该洞的价值才可继续打相连的下面的洞(每个士兵只能打一个洞)&#xff…

微信小程序自定义组件之Picker组件

微信小程序开发交流qq群 173683895 承接微信小程序开发。扫码加微信。 需求: 通过JS条件判断,满足条件就弹出Picker给用户选择一个数组里面的数据。 有些朋友可能会有疑问: 1.为什么要使用自定义的Picker组件,不是有原生的组…

kotlin ++ --_顺便说一句-探索Kotlin代表团

kotlin --by Adam Arold亚当阿罗德(Adam Arold) 顺便说一句-探索Kotlin代表团 (By the way — exploring delegation in Kotlin) Kotlin has an interesting keyword, by, which can be used for delegation. There is a lot of confusion around it, so in this article we’…

网页制作之html基础学习3-css样式表

样式:CSS(Cascading Style Sheets,层叠样式表),作用是美化HTML网页。 在样式里面用 /* */ 进行注释。 1、样式表的基本概念 1.1、样式表分类 1、内联样式表 和html联合显示,控制精确,但是可重用性差&#…

Mac OS X 下查看和设置JAVA_HOME

原文链接 : http://blog.csdn.net/done58/article/details/51138057 1, 查看Java版本 打开Mac电脑,查看JAVA版本,打开终端Terminal,通过命令行查看笔者的java版本:: [html] view plaincopy bogon:~ donny$ java -vers…

微信小程序获取用户设备的信息

微信小程序开发交流qq群 173683895 承接微信小程序开发。扫码加微信。 可以获取用户的手机型号,手机操作系统,微信版本,屏幕宽高等等。 Object wx.getSystemInfoSync() wx.getSystemInfo 的同步版本 返回值 Object res 属性类型说明最…

php 命令执行crud_如何使用原始JavaScript执行CRUD操作

php 命令执行crudby Zafar Saleem通过Zafar Saleem 如何使用原始JavaScript执行CRUD操作 (How to perform CRUD operations using vanilla JavaScript) Nowadays there are a number of JavaScript frameworks around such as React, Angular, Vue and so on. They all offer …

关于手机系统信息的总结

获取IMEI号: /*** 获取IMEI号* * Description:* param param activity* param return* return String*/public static String getIMEI(Activity activity) {TelephonyManager manager (TelephonyManager) activity.getSystemService(Context.TELEPHONY_SERVICE);return manage…

pat1011. World Cup Betting (20)

1011. World Cup Betting (20) 时间限制400 ms内存限制65536 kB代码长度限制16000 B判题程序Standard作者CHEN, YueWith the 2010 FIFA World Cup running, football fans the world over were becoming increasingly excited as the best players from the best teams doing b…

如何清空定时器

微信小程序开发交流qq群 173683895 承接微信小程序开发。扫码加微信。 看代码 var aaaa; //利用slice function truncate(arr) {return arr.slice(0, -1); } Page({data: {},onShow() {console.log(yyyyyyyyyyyyyyyyyyy)clearInterval(aaaa)aaaa setInterval(function () {…

如何解决JavaScript中的根查找

介绍 (Introduction) I’ve been wanting to write about this topic for a while now. I recently had the opportunity to work on simulating the GoalSeek functionality of Excel for a web application. I found the whole purpose of GoalSeek and how it works fascina…

菜单样式1:鼠标悬停向下弹出列表

JS部分:var qcloud{};$([_t_nav]).hover(function(){var _nav $(this).attr(_t_nav);clearTimeout( qcloud[ _nav _timer ] );qcloud[ _nav _timer ] setTimeout(function(){$([_t_nav]).each(function(){$(this)[ _nav $(this).attr(_t_nav) ? addClass:remo…

JS 保持数组长度为3位并且值不重复

微信小程序开发交流qq群 173683895 承接微信小程序开发。扫码加微信。 需求:保存用户搜索的3次历史记录,新的代替旧的,重复的不录入。 这里有几种情况: 1.第一次搜索,搜索的历史缓存数组为空,就直接添…

Mysql 查询 字符串 (索引和通配符)

需要查询的 Mission_Info 字段 值 CYVR-0220-1240-ZYTX-1415-1740-ZUUU-9999-9999-ZZZZ-9999-9999-ZZZZ SELECT Mission_Info FROM flightplan WHERE Mission_Info LIKE %CYVR-____-____% AND Mission_Info LIKE %-ZYTX%AND instr(Mission_Info, CYVR) <instr(Mission_In…

使用Python和NLTK的自然语言处理(NLP)教程

Natural language processing (NLP) is a branch of artificial intelligence that helps computers understand, interpret, and manipulate human language.自然语言处理(NLP)是人工智能的一个分支&#xff0c;可以帮助计算机理解&#xff0c;解释和操纵人类语言。 This vid…

微信公众号网页获取用户信息

微信小程序开发交流qq群 173683895 承接微信小程序开发。扫码加微信。 效果图 html 代码&#xff1a; <!DOCTYPE html> <html><head><meta name"viewport" content"widthdevice-width, initial-scale1.0, user-scalableno, minimum-sc…

React Native —— App

使用 React Native 作为 app 框架&#xff0c;Redux 作为数据层&#xff0c;因此我们需要选用一些支持性的技术和工具&#xff1a; 开源的 Parse Server 做数据存储 - 运行在 Node.js 上。Flow 用来做 React Native 的 JavaScript 输入错误检查&#xff0c;防止低级的输入错误。…

数据库访问性能优化

数据库访问性能优化 转载于:https://www.cnblogs.com/daishuguang/p/4707357.html

如何使用日志进行程序调试_如何使用日志节省调试时间

如何使用日志进行程序调试by Maya Gilad通过Maya Gilad 如何使用日志节省调试时间 (How to save hours of debugging with logs) A good logging mechanism helps us in our time of need.一个 良好的日志记录机制可以在需要时帮助我们。 When we’re handling a productio…

(转)线程的同步

Java线程&#xff1a;线程的同步-同步方法线程的同步是保证多线程安全访问竞争资源的一种手段。线程的同步是Java多线程编程的难点&#xff0c;往往开发者搞不清楚什么是竞争资源、什么时候需要考虑同步&#xff0c;怎么同步等等问题&#xff0c;当然&#xff0c;这些问题没有很…

wpf浏览器应用程序发布后获取当前应用地址

AppDomain.CurrentDomain.ApplicationIdentity.CodeBase 获取作为URL的部署清单的位置 Eg&#xff1a;发布前地址为E:\PROJECTWORK\LandaV8\bin\Debug\xxxxx.xbap&#xff08;xxxxx.xbap为部署站点下的文件&#xff09;&#xff0c;部署后获取的地址为http://192.168.1.1/xxx…

微信小程序获取用户手机号,后端php实现 (前后端完整代码附效果图)

微信小程序开发交流qq群 173683895 承接微信小程序开发。扫码加微信。 如图&#xff1a; 小程序代码&#xff1a; 第一步&#xff0c;登录&#xff0c;获取用户的 session_key&#xff1b; 第二步&#xff0c;点击按钮调用 bindgetphonenumber 事件&#xff0c;通过该事件…

pytorch与keras_Keras vs PyTorch:如何通过迁移学习区分外星人与掠食者

pytorch与kerasby Patryk Miziuła通过PatrykMiziuła Keras vs PyTorch&#xff1a;如何通过迁移学习区分外星人与掠食者 (Keras vs PyTorch: how to distinguish Aliens vs Predators with transfer learning) This article was written by Piotr Migdał, Rafał Jakubanis…

Ubuntu 16.04安装QQ(不一定成功)

注意1&#xff1a;如果是刚新装的系统&#xff0c;可以正常安装&#xff0c;但是&#xff0c;如果你已经装了很多软件&#xff0c;千万不要安装&#xff0c;因为会把系统上一般的依赖包和你之前装的软件全部卸载掉&#xff01;甚至将桌面Dock都会卸载&#xff01;最终只能重装U…