登录-微信小程序
App.js中
const TOKEN = 'token'
App({
//全局变量
globalData: {
token: ''
},
onLaunch: function() {
// 1.先从缓存中取出token
const token = wx.getStorageSync(TOKEN)
// 2.判断token是否有值
if (token && token.length !== 0) {
this.check_token(token) //token有值,验证token
} else {
this.login() //token无值,登录操作
}
// 验证token
check_token(token){
wx.request({
url: 'http://123.207.32.32:3000/auth',
method: 'post',
header: {
token
},
success: res => {
if(!res.data.errCode){
this.globalData.token = token
}
},
fail: err => {
console.log(err)
}
})
},
// 登录
login() {
wx.login({
success: res => {
// 发送 res.code 到后台换取 openId, sessionKey, unionId
const code = res.code
wx.request({
url: 'http://123.207.32.32:3000/login',
method: 'post',
data: {
code
},
success: res => {
// console.log(res)
const token = res.data.token
this.globalData.token = token
wx.setStorageSync(TOKEN, token)
}
})
}
})
}
})