小程序封装

小程序封装

实现自动登录,session失效自动登录并重新请求,本地保存登录态,接口统一管理,最小化重复代码

使用方法

1
2
3
4
5
6
7
//index.js
const { request } = require('../../utils/util.js')
...
request('GETselectPage', { pageIndex }, res => {
//请求成功执行函数
})
...

实现方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
//util.js
const { api, noRegisterApi, baseUrl } = require('./interface.js')

const unsentXhr = []

let logging = false

const request = (url, data = {}, success = () => { }, fail = () => { }, complete = () => { }) => {
const sessionId = wx.getStorageSync('sessionId'),
goLogin = () => {
unsentXhr.push(() => request(url, data, success, fail, complete))
return login()
}

if (!sessionId) return goLogin()

const method = url.startsWith('GET') ? 'GET' : 'POST'
let header = { 'wxa-sessionid': sessionId, "X-Requested-With": "XMLHttpRequest" }
if (method === 'POST') header = { ...header, "Content-Type": "application/x-www-form-urlencoded" }

return wx.request({
url: api[url], data, header, method, dataType: 'json',
success(...arg) {
const { data: { code, msg } } = arg[0]
if (code === 500) return wx.showToast({ title: '服务器错误', icon: 'loading' })
if (msg.includes('wxa_session')) return goLogin()
success(...arg)
}, fail(...arg) {
wx.showToast({ title: '服务器错误', icon: 'loading' })
fail(...arg)
}, complete,
})
}

function login() {
if (logging) return
logging = true
wx.login({
success(res) {
wx.request({
url: api.login,
data: { code: res.code },
header: {
"Content-Type": "application/x-www-form-urlencoded",
"X-Requested-With": "XMLHttpRequest"
},
method: 'POST', dataType: 'json',
success(res) {
if (res.data.code !== 0) return wx.showToast({ title: '服务器错误', icon: 'loading' })
const { data: { body: { sessionId } } } = res
wx.setStorageSync('sessionId', sessionId)
unsentXhr.forEach(xhr => xhr())
unsentXhr.length = 0
},
complete() { logging = false }
})
}
})
}

module.exports = {
request,
login
}



//app.js

const { login } = require('utils/util.js')
App({
onLaunch () {
wx.getStorage({
key: 'sessionId',
success (res) {
if (!res.data) login()
}
})
},
globalData: {},
})
坚持原创技术分享,您的支持将鼓励我继续创作!