refactor: 重构微信小程序从云开发迁移至后端API
将云数据库操作改为调用后端API接口 提取登录失败处理逻辑到单独方法 添加环境配置和API请求工具类 移除云开发相关配置
This commit is contained in:
@@ -1,16 +1,8 @@
|
||||
// app.js
|
||||
const { BASE_URL, API } = require('./utils/config')
|
||||
|
||||
App({
|
||||
onLaunch() {
|
||||
if (!wx.cloud) {
|
||||
console.error('请使用 2.2.3 或以上的基础库以使用云能力')
|
||||
} else {
|
||||
wx.cloud.init({
|
||||
traceUser: true
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
|
||||
// 自动静默登录:wx.login 获取 code,再请求后端接口换取 openid
|
||||
this.silentLogin()
|
||||
},
|
||||
@@ -22,66 +14,55 @@ App({
|
||||
this.loginWithCode(loginRes.code)
|
||||
} else {
|
||||
console.error('wx.login 失败', loginRes.errMsg)
|
||||
this.globalData.isLoggedIn = false
|
||||
this.globalData.loginFailed = true
|
||||
if (this.loginReadyCallback) {
|
||||
this.loginReadyCallback(null)
|
||||
}
|
||||
this.handleLoginFail()
|
||||
}
|
||||
},
|
||||
fail: (err) => {
|
||||
console.error('wx.login 调用失败', err)
|
||||
this.globalData.isLoggedIn = false
|
||||
this.globalData.loginFailed = true
|
||||
if (this.loginReadyCallback) {
|
||||
this.loginReadyCallback(null)
|
||||
}
|
||||
this.handleLoginFail()
|
||||
}
|
||||
})
|
||||
},
|
||||
|
||||
loginWithCode(code) {
|
||||
wx.request({
|
||||
url: 'https://xcx.yun.588580.xyz/api/wx-mini/login',
|
||||
url: BASE_URL + API.LOGIN,
|
||||
method: 'GET',
|
||||
data: { code },
|
||||
success: (res) => {
|
||||
const result = res.data
|
||||
if (result && result.code === 0 && result.data) {
|
||||
const openid = result.data.openid
|
||||
const userInfo = {
|
||||
openid,
|
||||
openid: result.data.openid,
|
||||
sessionKey: result.data.session_key,
|
||||
unionid: result.data.unionid || ''
|
||||
}
|
||||
|
||||
this.globalData.userInfo = userInfo
|
||||
this.globalData.isLoggedIn = true
|
||||
wx.setStorageSync('userInfo', userInfo)
|
||||
|
||||
if (this.loginReadyCallback) {
|
||||
this.loginReadyCallback(userInfo)
|
||||
}
|
||||
} else {
|
||||
console.error('后端登录失败', result)
|
||||
this.globalData.isLoggedIn = false
|
||||
this.globalData.loginFailed = true
|
||||
if (this.loginReadyCallback) {
|
||||
this.loginReadyCallback(null)
|
||||
}
|
||||
this.handleLoginFail()
|
||||
}
|
||||
},
|
||||
fail: (err) => {
|
||||
console.error('请求后端登录接口失败', err)
|
||||
this.globalData.isLoggedIn = false
|
||||
this.globalData.loginFailed = true
|
||||
if (this.loginReadyCallback) {
|
||||
this.loginReadyCallback(null)
|
||||
}
|
||||
this.handleLoginFail()
|
||||
}
|
||||
})
|
||||
},
|
||||
|
||||
handleLoginFail() {
|
||||
this.globalData.isLoggedIn = false
|
||||
this.globalData.loginFailed = true
|
||||
if (this.loginReadyCallback) {
|
||||
this.loginReadyCallback(null)
|
||||
}
|
||||
},
|
||||
|
||||
globalData: {
|
||||
userInfo: null,
|
||||
isLoggedIn: false,
|
||||
|
||||
Reference in New Issue
Block a user