In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >
Share
Shulou(Shulou.com)06/01 Report--
The front-end request token expires when refreshing token processing is what, many novices are not very clear about this, in order to help you solve this problem, the following small series will explain in detail for everyone, there are people who need this can learn, I hope you can gain something.
In front-end development, we often encounter the use of tokens. The role of tokens is to verify whether the user is logged in, so when requesting resources that can only be viewed in the login state, we need to carry tokens.
Generally, the token set by the backend interface is time-limited and will expire after timeout. After the expiration, the processing strategy will generally do two kinds of processing. One is to directly jump to the login page and log in again.
The flow chart is as follows:
Another is to refresh the token automatically if it returns a token expiration message, and then continue to complete the outstanding request operation.
The flow chart is as follows:
But at this time we have to consider a problem, usually a page is not just sent an asynchronous request, may send multiple asynchronous requests at the same time, the following we use a flowchart to describe a page sent multiple requests at the same time, and multiple requests need to verify token, as shown below:
We found that if the above situation occurs, token will be refreshed many times, except for the first time to judge token failure, refresh token operation, the rest of the refresh token is redundant, how should we deal with it?
First of all, let's simulate the above actions of obtaining token and refreshing token according to the real scene:
For example, there are five people buying tickets at the same time. In order to be similar to the scene of refreshing token, five people buy tickets from five channels. They don't know that there are four other people who also buy tickets. These five people all find that there is no one at the ticket window. At this time, according to the scene just now, the following situation may occur. Each of the five people will call the ticket seller and then complete the ticket purchase. In another case, one of them will call the ticket seller and stick a note behind the ticket window. Tell the others that the conductor will be with you shortly and that the other four will just have to wait.
The first scenario is illustrated as follows:
这种场景会出现上面情况呢?可能会来五个售票员。。。
第二种场景图示如下:
结合买票与刷新token的场景,我们再次观察上面完成的伪代码,我么需要如下几个工具,纸条,观察者。
纸条应该是一个变量,其他用户通过这个变量来判断是否去刷新token,观察者,当售票员回来,或者token刷新完成,其他几个用户再次去完成业务逻辑。
最终的业务流程图如下:
伪代码实现如下:
const axios = require("axios");// 封装请求function request(url, options) { const token = localStorage.getItem('token'); const defaultOptions = { headers: { Authorization: `Bearer ${token}`, }, withCredentials: true, url: url, baseURL: BASE_URL, }; const newOptions = { ...options, ...defaultOptions }; return axios.request(newOptions) .then(checkStatus) .catch(error => console.log(error));}
// 默认纸条let isRefreshing = true;function checkStatus(response) { if (response && response.code === 1002) { // 刷新token的函数,这需要添加一个开关,防止重复请求 if(isRefreshing){ refreshTokenRequst() } isRefreshing = false; // 将当前的请求保存在观察者数组中 const retryOriginalRequest = new Promise((resolve) => { addSubscriber(()=> { resolve(request(url, options)) }) }); return retryOriginalRequest; }else{ return response; }}
function refreshTokenRequst(){ let data; const refreshToken = localStorage.getItem('refreshToken'); data={ authorization: 'YXBwYXBpczpaSWxhQUVJdsferTeweERmR1praHk=', refreshToken, } axios.request({ baseURL: BASE_URL, url:'/app/renewal', method: 'POST', data, }).then((response)=>{ // 刷新完成后,将刷新token和refreshToken存储到本地 localStorage.setItem('refreshToken',response.data.refreshToken); localStorage.setItem('token',response.data.token); // 并且将所有存储到观察者数组中的请求重新执行。 onAccessTokenFetched(); // 纸条撕掉 isRefreshing = true; });}
// 观察者let subscribers = [];function onAccessTokenFetched() { subscribers.forEach((callback)=>{ callback(); }) subscribers = [];}
function addSubscriber(callback) { subscribers.push(callback)}
可以看到纸条相当于变量isRefreshing,观察者相当于数组subscribers。以上便是token失效时的处理策略,如果你有其他想法欢迎留言。
看完上述内容是否对您有帮助呢?如果还想对相关知识有进一步的了解或阅读更多相关文章,请关注行业资讯频道,感谢您对的支持。
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.