Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Vue eliminates repeated prompts to refresh pages when Token expires. How to solve the problem?

2025-03-29 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

This article mainly introduces "how to solve the problem of Vue eliminating repeated prompts for refreshing pages when Token expires". In daily operation, it is believed that many people have doubts about how to solve the problem when Vue eliminates repeated prompts for refreshing pages when Token expires. The editor consulted all kinds of materials and sorted out simple and easy-to-use operation methods. I hope it will be helpful for you to answer the question of "Vue eliminates the problem of repeated prompts for refreshing pages when Token expires". Next, please follow the editor to study!

When the token expires, refresh the page. If the page initiates multiple requests to the backend when loading, it will repeat the alarm prompt. After processing, it will only prompt the alarm once.

1. Problem phenomenon

The    page has not been operated for a long time, and when the page is refreshed, the first pop-up "token is invalid, please log in again!" Prompt, then jump to the login page, and then pop up n "Token expired" back-end return messages.

2. Cause analysis.

The current page of    is initialized, and there are multiple calls to query the system parameters from the backend, as follows:

Created () {/ / = / / gets the required system parameters. Note: the getParameterClass method loads data asynchronously. / / if you need to print observation, you need to process / / obtain the parameter category this.commonFuncs.getParameterClass (this, "user_type", "userTypeList", "userTypeMap") of the user type through watch; / / obtain the parameter category for of the user status (var I = 0; I)

< this.userStatusList.length; i++){ var item = this.userStatusList[i]; var mapKey = parseInt(item.itemKey); this.userStatusMap.set(mapKey, item); } // 获取性别的参数类别 this.commonFuncs.getParameterClass(this,"gender","","genderMap"); // 获取部门的参数类别 this.commonFuncs.getParameterClass(this,"department","","deptMap"); // 获取角色的参数类别 this.commonFuncs.getParameterClass(this,"role","","roleMap"); // 查询用户记录 this.queryUsers(); },   这些请求,是axios调用,是异步执行的,因此,刷新页面时,这些请求几乎立即就发出了。然后,这些请求的响应会陆续返回。   响应首先被下面的response拦截器处理: // token相关的response拦截器instance.interceptors.response.use(response =>

{if (response) {switch (response.data.code) {case 3: / token is empty case 4: / / token expired case 5: / / token incorrect localStorage.clear (); / / Delete user information alert ("token is invalid, please log in again!") / / to jump to landing page router.replace ({path: "/ login",}); break; case 6: / / disable access / / jump to router.replace ({path: "/ forbidden",}); break; default: break }} return response;}, error = > {return Promise.reject (error.response.data.message) / / returns the error message returned by the API})

   then enters the code for the request call:

This.instance.getParameterClass (this.$baseUrl, {"classKey": classKey}) .then (res = > {/ / console.log (res.data); if (res.data.code = = parent.global.SucessRequstCode) {/ / if the query is successful / / successful processing code.} else {alert (res.data.message) ) .catch (error = > {/ / alert ("failed to query system parameters!") ; console.log (error);})

   's current problem:

For a request, if the token expires, the reponse interceptor first pops up an alarm prompt, and then there is a prompt for the caller:

Alert (res.data.message)

This repeats itself.

For multiple requests issued at the same time, you need to be marked to remember whether this token expiration has been prompted, only once, and if so, there is no need to prompt.

3. Solution

3.1. eliminate repeated prompts for token expiration at interceptors and request calls

   writes a public method to check whether the return code is intercepted and put it in the / src/common/commonFuncs.js file as follows:

/ * the return code that determines whether it is intercepted and processed, and returns true, indicating that it is intercepted. * the function of this method is to call. There is no need to handle the error message of intercepted error codes * @ param {error codes of the request} code * / isInterceptorCode (code) {switch (code) {case 3: / / token is empty case 4: / / token expired case 5: / / token incorrect case 6: / / disable access to return true Default: break;} return false;}

   then all calls are processed for unsuccessful returns as follows:

If (! this.commonFuncs.isInterceptorCode (res.data.code)) {alert (res.data.message);}

In this way,    eliminates repeated alarms for intercepting and invoking processing.

3.2. Multiple requests are prompted for processing only once.

   adds the token invalid flag to the global variable file / src/common/global.js, as follows:

/ / Global variable export default {/ / request successful return code SucessRequstCode:0, / / token invalid tag TokenInvalidFlag: 0}

   then modifies the interceptor code:

/ / token-related response interceptor instance.interceptors.response.use (response = > {if (response) {switch (response.data.code) {case 0: / normal / / reset token invalid flag set global.TokenInvalidFlag = 0; break Case 3: / / token is empty case 4: / / token expired case 5: / / token is incorrect localStorage.clear (); / / Delete user information if (global.TokenInvalidCounter = = 0) {alert ("token is invalid, please log in again!");} / / token invalid tag set 1 global.TokenInvalidFlag = 1 / / to jump to landing page router.replace ({path: "/ login",}); break; case 6: / / disable access / / jump to router.replace ({path: "/ forbidden",}); break; default: break }} return response;}, error = > {return Promise.reject (error.response.data.message) / / returns the error message returned by the API})

When    receives the token expiration message for the first time (TokenInvalidFlag=0 at this time), it prompts it, and then sets it to 1 (TokenInvalidFlag=1 at this time). The responses of subsequent requests will not be prompted in the alarm. It is reset to 0 until the return code is received successfully, which means that the re-login is successful.

   has been tested, and this processing achieves the desired effect, that is, when the token expires, the page will be refreshed and only one alarm will be prompted.

At this point, the study on "Vue eliminates the problem of repeated prompts for refreshing pages when Token expires" is over. I hope to be able to solve everyone's doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!

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.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report