-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.js
110 lines (108 loc) · 2.58 KB
/
app.js
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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
//app.js
App({
onLaunch: function () {
const userInfo = wx.getStorageSync('userInfo') || {}
if (!userInfo.userToken) {
//登录
this.loginMini()
} else {
// 获取用户信息
this.getUserInfo(userInfo.userToken)
}
},
loginMini: function () {
wx.login({
success: (res) => {
if (res.code) {
// 登录成功,用code换openid
this.getOpenId(res.code)
} else {
wx.showModal({
title: '提示',
content: '自动登录失败,是否重新登录',
cancelText: '否',
confirmText: '是',
success: () => {
this.loginMini()
}
})
}
}
})
},
getUserInfo: function (userToken) {
this.doFetch({
url: '/api/user-info',
params: {
token: userToken
},
success: (res) => {
this.setUserInfo(res.data || null)
},
fail: (res) => {
console.log(res)
}
})
},
getOpenId: function (code) {
this.doFetch({
url: '/api/wx-login',
method: 'post',
params: {
code
},
success: (res) => {
this.setUserInfo(res.data || null)
},
fail: (res) => {
console.log(res)
}
})
},
setSkin: function (skin) {
this.globalData.skin = skin
wx.setStorageSync('skin', skin)
},
doFetch: function ({url = '', method = 'GET', params = {}, header = {}, success = () => {}, fail}) {
const BASE_URL = 'http://127.0.0.1:8787'
wx.request({
url: BASE_URL + url,
method,
data: params,
header: {
...header,
'Authorization': 'Bearer' + (this.globalData.userInfo ? this.globalData.userInfo.userToken || '' : '')
},
success: (res) => {
if (res.statusCode >= 200 && res.statusCode < 300 || res.statusCode === 304) {
success(res)
} else {
if (fail) {
fail(res)
} else {
wx.showToast({
title: '服务器错误',
image: '/assets/images/error.png',
duration: 3000
})
}
}
},
fail: (res) => {
wx.showToast({
title: '服务器异常',
image: '/assets/images/error.png',
duration: 3000
})
}
})
},
setUserInfo: function (info) {
this.globalData.userInfo = info || null
wx.setStorageSync('userInfo', info || null)
},
globalData: {
userInfo: wx.getStorageSync('userInfo') || null,
skin: wx.getStorageSync('skin') || 'dark-skin'
}
})