框架:vue3.0
混合开发
需求:根据后台接口是否返回1401来刷新token,token刷新后重新调上一个接口
封装jsBridge
function setupWebViewJavascriptBridge(callback) {
if (window.WebViewJavascriptBridge) {
return callback(WebViewJavascriptBridge);
} else {
document.addEventListener('WebViewJavascriptBridgeReady', function () {
callback(WebViewJavascriptBridge)
}, false);
if (window.WVJBCallbacks) {
return window.WVJBCallbacks.push(callback);
}
window.WVJBCallbacks = [callback];
var WVJBIframe = document.createElement('iframe');
WVJBIframe.style.display = 'none';
WVJBIframe.src = 'https://__bridge_loaded__';
document.documentElement.appendChild(WVJBIframe);
setTimeout(function () {
document.documentElement.removeChild(WVJBIframe)
}, 0)
}
}
//初始化
setupWebViewJavascriptBridge(function (bridge) {
try {
bridge.init(function (message, callback) {
callback(null);
})
} catch (e) { }
});
export default {
//js调APP方法 (参数分别为:app提供的方法名 传给app的数据 回调)
callhandler: function (method, params, callback) {
setupWebViewJavascriptBridge(function (bridge) {
bridge.callHandler(method, params, callback)
})
},
// APP调js方法 (参数分别为:js提供的方法名 回调)
registerHandler(method, callback) {
setupWebViewJavascriptBridge((bridge) => {
bridge.registerHandler(method, (data, responseCallback) => {
callback(data, responseCallback)
})
})
}
}
按需引入
import jsBridge from '地址';
在request.js的请求拦截部分处理
1.定义调用jsBridge的方法
function reFreshToken(){
return new Promise(function(resolve,reject){
JsBridge.callhandler('refreshToken',{},function(appResponse){
resolve(appResponse) ;
});
}) ;
};
2.定义公共方法去调用reFreshToken,
function handleRefreshToken(config){
return reFreshToken().then(res=>{
let data=JSON.parse(res);
setAccessToken(data.access_token); //将accessToken存sessionStorage
const {token} =data.access_token;
config.headers['access-token']=getAccessToken();
config.baseURL='';
request.forEach(cb=>{
cb(token);
});
requests = [] ;
return request(config);
}).catch(err=>{
console.log(err,'刷新token错误')
}).finally(()=>{
isRefreshing=false; //标志,为了防止重复调用
})
}
3.在请求拦截和error里面判断是否返回1401
if(response.data.code === 1401){
if(!isRefreshing){
isRefreshing=true;
handleRefreshToken(config);
};
};
网友评论