import Request from './request'
import Config from '@/config.js'
const http = new Request()
http.setConfig((config) => { /* 设置全局配置 */
config.baseUrl = Config.baseUrl;
return config
})
http.validateStatus = (response) => {
return response.statusCode === 200 || response.statusCode === 401;
}
http.interceptor.request((config, cancel) => { /* 请求之前拦截器 */
if(config.method === "GET"){
// config.params.only_time = parseInt(new Date().getTime()/1000);
}else if(config.method === "POST"){
// config.data.only_time = parseInt(new Date().getTime()/1000);
}
config.header = {
...config.header,
// "blade-auth": uni.getStorageSync('blade-auth') || '',
"User-Type": "staff",
"Tenant-Id":"156245",
"Authorization": "Basic c3dvcmQ6c3dvcmRfc2VjcmV0",
}
if(uni.getStorageSync('blade-auth')){
let obj = {
"blade-auth": uni.getStorageSync('blade-auth') || '',
}
Object.assign(config.header,obj)
}
return config
})
http.interceptor.response( async (response) => { /* 请求之后拦截器 */
const statusCode = response.statusCode;
if (statusCode === 401) {
return await doRequest(response); //刷新 token 方法
}else{
return response.data
}
}, (response) => { // 请求错误做点什么
return response
})
export {
http
}
// 刷新 token 方法
async function doRequest(response) {
uni.setStorageSync("blade-auth", "");
let url = Config.locatBladeAuth + "oauth/token"
let paramData = {
'grant_type':'refresh_token',
'scope':'all',
'refresh_token': uni.getStorageSync('refresh_token') || '',
}
let opitons ={
header:{
'content-type': 'application/x-www-form-urlencoded;charset=UTF-8'
}
};
const res = await http.post(url, paramData,opitons);
if(res.access_token){
uni.setStorageSync("blade-auth", "bearer "+ res.access_token);
uni.setStorageSync("access_token", res.access_token);
uni.setStorageSync("refresh_token", res.refresh_token);
response.config.header['blade-auth'] = "bearer "+res.access_token
response.config.header['User-Type'] = 'staff'
response.config.header['Tenant-Id'] = '156245'
response.config.header['Authorization'] = "Basic c3dvcmQ6c3dvcmRfc2VjcmV0"
const resold = await http.request(response.config)
return resold
}else{
uni.removeStorageSync('blade-auth');
uni.removeStorageSync('access_token');
uni.removeStorageSync('refresh_token');
uni.removeStorageSync("userInfo");
uni.showToast({
title: '登陆过期请重新登陆',
icon:'none'
})
setTimeout(()=>{
uni.reLaunch({
url:'/pages/login/studentLogin'
})
},1000)
}
}
2021-09-15uniapp 无痛刷新ToKen
最后编辑于 :
©著作权归作者所有,转载或内容合作请联系作者
- 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
- 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
- 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...