1、判断登录是否过期(主要判断token、有效时间、是否登录的状态)
2、过期操作的流程获取cache_key缓存
执行成功的回调
(1)在用户授权成功的情况下调用wx.getUserInfo
(2)将用户信息作为参数调用后端的登录接口,执行登录成功的回调重新保存token、userinfo、expiresTime(有效时间)、缓存wx.setStorage({ key: 'cache_key', data: res.data.cache_key })
config.js
module.exports = {
// 请求域名 格式: https://您的域名
HTTP_REQUEST_URL:'https://******.cn',
// 请求头
HEADER:{
'content-type': 'application/json'
},
// 回话密钥名称
TOKENNAME: 'Authori-zation',
}
request.js
import util from './util.js';
import authLogin from './autuLogin.js';
import { HEADER , TOKENNAME} from './../config.js';
/**
* 发送请求
*/
export default function request(api, method, data, {noAuth = false, noVerify = false})
{
let Url = getApp().globalData.url, header = HEADER;
if (!noAuth) {
//登录过期自动登录
if (!util.checkLogin()) return authLogin().then(res => { return request(api, method, data, { noAuth, noVerify}); });
}
if (getApp().globalData.token) header[TOKENNAME] = 'Bearer ' + getApp().globalData.token;
return new Promise((reslove, reject) => {
wx.request({
url: Url + '/api/' + api,
method: method || 'GET',
header: header,
data: data || {},
success: (res) => {
if (noVerify)
reslove(res.data, res);
else
reject(res.data.msg || '系统错误');
},
fail: (msg) => {
reject('请求失败');
}
})
});
}
['options', 'get', 'post', 'put', 'head', 'delete', 'trace', 'connect'].forEach((method) => {
request[method] = (api, data, opt) => request(api, method, data, opt || {})
});
演示
test.js编写接口:
import request from "./../utils/request.js";
export function test(obj){
return request.get("test",obj);
}
调用接口
import { test } from '../../../api/test.js';
Page({
data: {},
onLoad: function (options) {
this.test();
},
test: function(){
test({}).then(res => {
console.log(res);
});
}
})