小程序的登录流程
参考了网上大牛的登录流程总结出来的代码
https://juejin.im/post/5ae956366fb9a07aaa111037
自己整理的如下
const http = ({
url = '',
params = {},
method
} = {}) => {
wx.showLoading({
title: '加载中...'
})
return new Promise((resolve, reject) => {
wx.request({
url: url,
data: params,
method: method,
header: getHeader(),
complete: (res) => {
wx.hideLoading();
if (res.statusCode >= 200 && res.statusCode < 300) {
if (res.data.status < 0) {
//-1未登录
//-2过期
// 重新登录 并且重新请求
login().then(res => {
http({
url,
params,
method
}).then(res => {
resolve(res)
})
}).catch(() => {
//这里记录跳转登录之前的页面路径
wx.setStorage({
key: 'pageUrl',
data: {
pageUrl: getCurrentPageUrl(),
toPageUrl: getCurrentPageUrlWithArgs()
}
})
//去登录
wx.redirectTo({
url: '/pages/login/login',
})
})
} else {
//成功
resolve(res.data);
}
} else {
//跳转无网络页面
wx.navigateTo({
url: '../nofound/nofound'
})
}
}
})
})
}
function login() {
return new Promise((resolve, reject) => {
// 先调用 wx.login 获取到 code
wx.login({
success: res => {
// 再调用 wx.getUserInfo 获取到用户的一些信息 (一些基本信息,以及生成UnionID 所用到的信息 比如 rawData, signature, encryptedData, iv)
// 登录操作
let param = {
code: res.code
}
http({
url: 'url/auth_mini',
params: param,
method: 'post'
}).then(res => {
// 该为我们后端的逻辑 若res.item.access_token为登录成功,其他情况皆为异常 (视自身情况而定)
if (res.item.access_token) {
// 保存用户信息
wx.setStorage({
key: 'userinfo',
data: res.item.user_info
})
wx.setStorage({
key: "AccessToken",
data: res.item.access_token,
success: () => {
resolve(res)
}
})
} else {
reject(res)
}
}).catch(err => {
reject(res)
})
}
})
})
}
//获取token
const getHeader = () => {
try {
var token = wx.getStorageSync('AccessToken');
if (token) {
return {
'AccessToken': token
}
}
return {}
} catch (e) {
return {}
}
}
//获取页面路径
export function getCurrentPageUrl() {
const pages = getCurrentPages()
const currentPage = pages[pages.length - 1]
const url = `/${currentPage.route}`
return url
}
//获取页面路径与参数
export function getCurrentPageUrlWithArgs() {
const pages = getCurrentPages()
const currentPage = pages[pages.length - 1]
const url = currentPage.route
const options = currentPage.options
let urlWithArgs = `/${url}?`
for (let key in options) {
const value = options[key]
urlWithArgs += `${key}=${value}&`
}
urlWithArgs = urlWithArgs.substring(0, urlWithArgs.length - 1)
return urlWithArgs
}
module.exports = {
baseUrl,
apiList,
myUploadFile,
get(url, params = {}) {
return http({
url,
params
})
},
post(url, params = {}) {
return http({
url,
params,
method: 'post'
})
},
put(url, params = {}) {
return http({
url,
params,
method: 'put'
})
},
// 这里不能使用 delete, delete为关键字段
myDelete(url, params = {}) {
return http({
url,
params,
method: 'delete'
})
}
}
该文件为api.js
调用:
//先引用api.js
const api = require('../../utils/api.js');
//参数
let params = {}
api.get(params,'url').then(res =>{})
api.post(params,'url').then(res =>{})