axios全局拦截响应

在系统开发过程中,若遇到长时间未操作,则需要将页面跳转到登录页面。因为现在都是前后端分离的开发模式,路由跳转都交给前端,而后端只返回一个报错信息,例如"errorMsg":"请登录",而前端需要做的事就是判断每一个接口的返回信息中的errorMsg是不是等于“请登录”,如果是,则跳转到登录页面。但想要达到此效果,总不可能需要对每一个接口的返回信息都进行判断,这样做太麻烦。这个时候就需要用到axios的全局配置了(我前端用的是vue框架,接口请求用的是axios)。

axios.interceptors.response.use(function (response) {  
    // 用户信息是否超时,重定向到登录页面  
    if (response.data.errorMsg== '请登录'){  
        localStorage.clear()  
        router.replace({  
                        path: '/login',  
                        query: {redirect: router.currentRoute.fullPath}  
                    })  
    }  
    return response  
}, function (error) {  
    // Do something with response error  
    return Promise.reject(error)  
})

  

posted @ 2018-05-22 16:19  code-luyf  阅读(4315)  评论(1编辑  收藏  举报