封装请求有两种: 一种是在服务端判断token是否失效,一种是在小程序端判断token是否过期,,
第二种在前端判断要简单些,,在拿到token的时候,并在前端设置一个token的过期时间的毫秒值,约定为多久,,
前端发起请求的时候,先拿到这个时间做判断,判断token是否过期,如果过期,就去请求token,,请求完成之后再发起这个请求,,
如果没有过期,就直接发起请求,,
const BASE_URL = "http://localhost:8080"
export const request = (options)=>{
return new Promise((resolve, reject)=>{
// 毫秒 :令牌过期时间
let login_expire_time = uni.getStorageSync("login_expire_time")
if (login_expire_time && login_expire_time >new Date().getTime()){
//
handleRequest(options,resolve,reject)
}else{
console.log("ccccccc")
uni.login({
provider:"weixin",
success:function (loginRes){
uni.request({
url:BASE_URL+"/mp/login",
data:{
code:loginRes.code
},
method:"POST",
header:{
"content-type":"application/x-www-form-urlencoded" // 将data当为key-value传递
},
success:(res)=>{
console.log(res,"res")
uni.setStorage({
key:"userinfo",
data:res.data.data,
success:function (){
// 登录完成之后,都去生成一个 login_expire_time
uni.setStorageSync("login_expire_time",new Date().getTime()+3600*1000)
// 重新请求url
handleRequest(options,resolve,reject)
}
})
}
})
}
})
}
})
}
const handleRequest = (options,resolve,reject)=>{
uni.request({
url: BASE_URL + options.url,
data:options.data,
method: options.method,
header: {
"content-type": "application/json",
"mp_token":uni.getStorageSync("userinfo").session_key,
"openid":uni.getStorageSync("userinfo").openid
},
success:function (res){
resolve(res.data)
},
fail:function (err){
reject(err)
},
complete:()=>{
uni.hideLoading()
}
})
}
第一种是请求后端,令牌过期,会返回401,没有登录,,前端收到401错误码之后,再去重试这个请求
import {showCustomToast, toast} from "@/utils/utils";
import User from "@/model/User";
const BASE_URL = "http://localhost:8082"
/**
*
* @param retryCount 重试次数 ,,401重试两次
*/
function request({url,data,method="GET",retryCount=0}){
console.log(data,"data",url)
return new Promise((resolve, reject)=>{
uni.request({
url:BASE_URL+url,
method:method,
data:data,
header:{
"Authorization":`Bearer `+uni.getStorageSync("token")
},
success:(res)=>{
// 判断code码
if (res.statusCode === 200){
if (res.data.code === 200){
if (res.data.msg){
toast(res.data.msg)
}
resolve(res.data.data)
}else{
if (res.data.msg){
// toast(res.data.msg,"error")
showCustomToast(res.data.msg)
}
resolve()
}
}else{
// 服务器报错 400 500
console.log(res,"res2342")
if (res.statusCode===401){
if (retryCount < 2){
// 没有登录
new Promise((resolve, reject)=>{
uni.login({
provider:"weixin",
success:function (loginRes){
console.log(loginRes.code)
User.loginApi(loginRes.code).then(res=>{
console.log(res,"res")
uni.setStorageSync("token",res)
resolve()
})
}
})
}).then(async res => {
setTimeout(async () => {
// 重发请求
const result = await request({url, data, method, retryCount: retryCount + 1})
console.log(result,"result")
resolve(result)
},1000)
})
}else{
toast(res.data.msg,"error")
reject()
}
}else{
// 400 500
toast(res.data.msg,"error")
reject()
}
// if (res.data.msg){
//
// toast(res.data.msg,"error")
// }
}
},
fail:(err)=>{
console.log(err,"err")
reject(err)
}
})
})
}
export default request