静默登录 、请求后台
import Cache from "../utils/cache";
let cacheObj = new Cache({expire : 7100})
export default class Http{
req({url,method="GET",data={},isAuth=true}){
let header = {}
if(isAuth){
let token = cacheObj.get('token')
if(token){
header.authorization =`Bearer ${token}`
}else{
return this.login().then(token=>{
cacheObj.set('token',token)
return this.req({url,method,data})
})
}
}
return new Promise(function(suc,fa){
let modain = "http://www.monthlx.com/api"
wx.request({
url:`${modain}/${url}`,
method:method,
data:data,
header:header,
dataType:"json",
success:res=>{
suc(res.data)
}
})
})
}
login(){
let _that = this
return new Promise(function(suc,fa){
wx.login({
success:res=>{
let code = res.code
_that.req({
url : 'wxlogin',
method:"POST",
data:{code},
isAuth:false
}).then(res=>{
suc(res.data)
})
}
})
})
}
}
缓存
export default class Cache{
constructor({expire=7200}){
return this.expire = new Date().getTime() + 1000 * expire
}
/**
* 设置缓存
* @param {*} key
* @param {*} value
*/
set(key,value){
let valueObj={
expire : this.expire,
value : value
}
wx.setStorageSync(key,valueObj)
}
/**
* 判断缓存是否存在
* @param {}} key
*/
has(key){
let valueObj = wx.getStorageSync(key)
if(valueObj){
let nowTime = new Date().getTime()
if(nowTime>valueObj.expire){
wx.removeStorageSync(key)
return false
}else{
return true
}
}else{
return false
}
}
/**
* 获取缓存
* @param {*} key
*/
get(key){
if(this.has(key)){
return wx.getStorageSync(key).value
}
}
/**
* 删除缓存
* @param {*} key
*/
del(key){
return wx.removeStorageSync(key)
}
}