因为项目性质问题,我们给项目设置了较短的登录有效时间,而当登录过期时用户在某一页面进行操作,如果该操作同时请求了多个请求,则会得到多条登录过期的报错提示。作为一个专业的前端,怎么可以允许这种情况发生呢,于是就有了今天文章的内容。
service.interceptors.response.use( (respon)=>{xxxxx}, (error) => { let status = JSON.parse(JSON.stringify(error.response)); //堆代码 duidaima.com //跳转失败,返回首页. if (status.data.code == "401") { Message({ message: status.data.message, type: "error", duration: 5 * 1000, }); router.push({ path: "/login", }); } return Promise.reject(error); } )如上,当接口返回401时,则表明接口登录失效,需要抛出message,这个过程中,如果同时有几个接口返回401则会有多少条message。这时,我们可以有什么办法可以处理同一类型的错误只报错一次呢?没错,这就是我们今天要讲的方法:缓存。
// errorCache.js // config = { // cacheTime: 'xxxx' // } const errorCache = {}; function isCacheError(error, config) { if ( errorCache[error.code] && !isExpire(errorCache[error.code].timestamp, config.cacheTime) ) { return true; } errorCache[error.code] = { timestamp: Date.now(), }; setTimeout(() => { delete errorCache[error.code]; }, config.cacheTime); return false; } function isExpire(timestamp, cacheTime) { return Date.now() - timestamp > cacheTime; } export default isCacheError;思路:
(error) => { let status = JSON.parse(JSON.stringify(error.response)); if (!isCacheError(status.data, { cacheTime: 5 * 1000 })) { if (status.data.code == "401") { Message({ message: status.data.message, type: "error", duration: 5 * 1000, }); router.push({ path: "/login", }); } } return Promise.reject(error); }总结