零、回顾
上节课我们主要学习了,wx.request这个接口,这节课我们复用原来已经实现的,微信一键登录代码
在拿到登录凭证以后,来调用/user/home接口,这节课我们主要实践操作,主要分步骤实现以下四个层次的功能。
1.复原代码,在登录后直接调用接口
2.如果已经登录,则不需要重复登录
3.在加一个接口调用,将登录逻辑剥离为一个方法
4.模块化,在其他页面中也可以使用
一、复原代码,在登录后直接调用接口
1.1 复原代码
index.wxml
<view class="page-section">
<text class="page-section__title">3.2 在登陆之后调用接口</text>
<view class="btn-area">
<button bindgetuserinfo="login" open-type="getUserInfo" type="primary">登录</button>
</view>
</view>
// 3.2 登录之后,调用接口
login(e) {
console.log(e);
let {
userInfo,
encryptedData,
iv
} = e.detail
console.log('userInfo', userInfo);
const requestLoginApi = (code) => {
//发起网络请求
wx.request({
url: 'http://localhost:3000/user/wexin-login2',
method: 'POST',
header: {
'content-type': 'application/json'
},
data: {
code: code,
userInfo,
encryptedData,
iv
},
success(res) {
console.log('请求成功', res.data)
let token = res.data.data.authorizationToken
wx.setStorageSync('token', token)
onUserLogin(token)
console.log('authorization', token)
},
fail(err) {
console.log('请求异常', err)
}
})
}
const onUserLogin = (token) => {
getApp().globalData.token = token
wx.showToast({
title: '登陆成功了',
})
}
wx.checkSession({
success() {
//session_key 未过期,并且在本生命周期一直有效
console.log('在登陆中');
let token = wx.getStorageSync('token')
if (token) onUserLogin(token)
},
fail() {
// session_key 已经失效,需要重新执行登录流程
wx.login({
success(res0) {
if (res0.code) {
requestLoginApi(res0.code)
} else {
console.log('登录失败!' + res.errMsg)
}
}
})
}
})
},
1.2 增加一个接口调用
index.js
login(e) {
// + 新增代码
const startOneRequest = (token)=>{
wx.request({
url: "http://localhost:3000/user/home",
header:{
'Authorization': `Bearer ${token}`
},
success(res) {
if (res.errMsg === "request:ok") console.log("login-home-success-res", res);
},
fail(err) {
if (/^request:fail/i.test(err.errMsg)) console.log("login-home-err", err);
},
complete(res) {
console.log("login-home-complete-res", res);
}
});
}
let {
userInfo,
encryptedData,
iv
} = e.detail
console.log('userInfo', userInfo);
const requestLoginApi = (code) => {
//发起网络请求
......
}
const onUserLogin = (token) => {
getApp().globalData.token = token
wx.showToast({
title: '登陆成功了',
})
// + 新增代码
startOneRequest(token);
}
wx.checkSession({
......
})
},
二、如果已经登录,则不需要重复登录
如果短时间内重复调用接口,此时已经成功登陆过了,再重复调用就是一种浪费,
接下来我们直接在本课源码中,加上一个判断
已经登录了就直接发起接口的请求
let token = wx.getStorageSync('token')
if (token) {
startOneRequest(token);
return
}
三、再增加一个接口调用,将登陆逻辑剥离为一个方法
前面实现的是一个接口调用,
如果同页面内,还有另外一个接口调用,
这个时候最好可以把登录的代码,给剥离出来,作为一个独立的方法然后共享。
<view class="page-section">
<text class="page-section__title">3.2 登录 & 请求</text>
<view class="btn-area">
<button bindgetuserinfo="startOneRequestWithLofinUtilMethod1" open-type="getUserInfo" type="primary">请求1</button>
<button bindgetuserinfo="startOneRequestWithLofinUtilMethod2" open-type="getUserInfo" type="primary">请求2</button>
</view>
</view>
startOneRequestWithLofinUtilMethod1(e) {
const startOneRequest = (token)=>{
wx.request({
url: "http://localhost:3000/user/home",
header:{
'Authorization': `Bearer ${token}`
},
success(res) {
if (res.errMsg === "request:ok") console.log("3.2--res1", res);
},
fail(err) {
if (/^request:fail/i.test(err.errMsg)) console.log("3.2--err1", err);
},
complete(res) {
console.log("3.2--complete1", res);
}
});
}
let token = wx.getStorageSync('token')
if (token) {
startOneRequest(token);
return
}
loginWithCallback(e, startOneRequest);
},
startOneRequestWithLofinUtilMethod2(e) {
const startOneRequest = (token) => {
wx.request({
url: "http://localhost:3000/user/home",
header: {
'Authorization': `Bearer ${token}`
},
success(res) {
if (res.errMsg === "request:ok") console.log("3.2--res2", res);
},
fail(err) {
if (/^request:fail/i.test(err.errMsg)) console.log("3.2--err2", err);
},
complete(res) {
console.log("3.2--complete2", res);
}
});
}
let token = wx.getStorageSync('token')
if (token) {
startOneRequest(token);
return
}
loginWithCallback(e, startOneRequest);
},
loginWithCallback(e,cb){
let {
userInfo,
encryptedData,
iv
} = e.detail
console.log('userInfo', userInfo);
const requestLoginApi = (code) => {
//发起网络请求
wx.request({
url: 'http://localhost:3000/user/wexin-login2',
method: 'POST',
header: {
'content-type': 'application/json'
},
data: {
code: code,
userInfo,
encryptedData,
iv
},
success(res) {
console.log('请求成功', res.data)
let token = res.data.data.authorizationToken
wx.setStorageSync('token', token)
onUserLogin(token)
console.log('authorization', token)
},
fail(err) {
console.log('请求异常', err)
}
})
}
const onUserLogin = (token) => {
getApp().globalData.token = token
wx.showToast({
title: '登陆成功了',
})
// startOneRequest(token);
if (cb && typeof cb == 'function') cb(token);
}
wx.checkSession({
success() {
//session_key 未过期,并且在本生命周期一直有效
console.log('在登陆中');
let token = wx.getStorageSync('token')
if (token) onUserLogin(token)
},
fail() {
// session_key 已经失效,需要重新执行登录流程
wx.login({
success(res0) {
if (res0.code) {
requestLoginApi(res0.code)
} else {
console.log('登录失败!' + res.errMsg)
}
}
})
}
})
},
四、模块化 在其他页面中也可以使用
现在已经实现了登录代码的复用,但是仅是在同一个页面去复用,
如果我们还有另外一个页面呢,接下来我们直接在本课的源码中
演示一下如何将登录代码模块化,在多个页面里面实现调用
/pages/api/index.wxml
<view class="page-section">
<text class="page-section__title">3.2 登录 & 请求</text>
<view class="btn-area">
<button bindgetuserinfo="startOneRequestWithLofinUtilMethod1" open-type="getUserInfo" type="primary">请求1</button>
<button bindgetuserinfo="startOneRequestWithLofinUtilMethod2" open-type="getUserInfo" type="primary">请求2</button>
<navigator url="/pages/api/other/other">other</navigator>
</view>
</view>
/pages/api/index.js
import loginWithCallback from "../../lib/login.js"
startOneRequestWithLofinUtilMethod1(e) {
const startOneRequest = (token)=>{
wx.request({
url: "http://localhost:3000/user/home",
header:{
'Authorization': `Bearer ${token}`
},
success(res) {
if (res.errMsg === "request:ok") console.log("3.2--res1", res);
},
fail(err) {
if (/^request:fail/i.test(err.errMsg)) console.log("3.2--err1", err);
},
complete(res) {
console.log("3.2--complete1", res);
}
});
}
let token = wx.getStorageSync('token')
if (token) {
startOneRequest(token);
return
}
loginWithCallback(e, startOneRequest);
},
startOneRequestWithLofinUtilMethod2(e) {
const startOneRequest = (token) => {
wx.request({
url: "http://localhost:3000/user/home",
header: {
'Authorization': `Bearer ${token}`
},
success(res) {
if (res.errMsg === "request:ok") console.log("3.2--res2", res);
},
fail(err) {
if (/^request:fail/i.test(err.errMsg)) console.log("3.2--err2", err);
},
complete(res) {
console.log("3.2--complete2", res);
}
});
}
let token = wx.getStorageSync('token')
if (token) {
startOneRequest(token);
return
}
loginWithCallback(e, startOneRequest);
},
/pages/api/other/other.wxml
<button bindgetuserinfo="startOneRequestWithLofinUtilMethod1" open-type="getUserInfo" type="primary">请求1</button>
<navigator open-type="navigateBack">back</navigator>
/pages/api/other/other.js
import loginWithCallback from "../../../lib/login.js"
startOneRequestWithLofinUtilMethod1(e) {
const startOneRequest = (token) => {
wx.request({
url: "http://localhost:3000/user/home",
header: {
'Authorization': `Bearer ${token}`
},
success(res) {
if (res.errMsg === "request:ok") console.log("3.2-other--res1", res);
},
fail(err) {
if (/^request:fail/i.test(err.errMsg)) console.log("3.2-other--err1", err);
},
complete(res) {
console.log("3.2-other--complete1", res);
}
});
}
let token = wx.getStorageSync('token')
if (token) {
startOneRequest(token);
return
}
loginWithCallback(e, startOneRequest);
},
lib/login.js
function loginWithCallback(e, cb){
let {
userInfo,
encryptedData,
iv
} = e.detail
console.log('userInfo', userInfo);
const requestLoginApi = (code) => {
//发起网络请求
wx.request({
url: 'http://localhost:3000/user/wexin-login2',
method: 'POST',
header: {
'content-type': 'application/json'
},
data: {
code: code,
userInfo,
encryptedData,
iv
},
success(res) {
console.log('请求成功', res.data)
let token = res.data.data.authorizationToken
wx.setStorageSync('token', token)
onUserLogin(token)
console.log('authorization', token)
},
fail(err) {
console.log('请求异常', err)
}
})
}
const onUserLogin = (token) => {
getApp().globalData.token = token
wx.showToast({
title: '登陆成功了',
})
// startOneRequest(token);
if (cb && typeof cb == 'function') cb(token);
}
wx.checkSession({
success() {
//session_key 未过期,并且在本生命周期一直有效
console.log('在登陆中');
let token = wx.getStorageSync('token')
if (token) onUserLogin(token)
},
fail() {
// session_key 已经失效,需要重新执行登录流程
wx.login({
success(res0) {
if (res0.code) {
requestLoginApi(res0.code)
} else {
console.log('登录失败!' + res.errMsg)
}
}
})
}
})
}
//写default,引入的时候不用写{}
export default loginWithCallback
五、总结
这节课我们主要进行了登录代码的封装,最终将登录代码模块化,放在了一个文件里面
但是在一个接口的回调函数中,再去调用另外一个函数,这种写法既不优雅也不简洁,
如果在一个业务逻辑中,涉及多个函数调用,像上面我们已经实现的这样一个代码就是这样。
在最糟糕的情况下,它涉及了wx.checkSession、wx.login、wx.request等多个接口的调用,函数之间的调用关系不清晰。
有一个基于Promise异步操作对象的编程模式,可以优化这种代码。
下节课我们就重点学习一下,如何基于Promise改造我们已经实现的登录代码,以及接口请求的功能。