在main.js的axios中配置响应拦截器,当token值不合法直接跳转到登录页

先上代码:

// 给axios配置响应拦截器
axios.interceptors.response.use(
  function(response) {
    // 当返回状态码表示token值无效时
    if (response.data.code === 4002) {
      Vue.prototype.$message.error('登录已过期,请重新登录')
      router.replace('/login')
    } else {
    // 其他情况
      return response.data
    }
  },
  function(error) {
    // 对响应错误做点什么
    return Promise.reject(error)
  }
)

最开始我的想法是在vue的main.js中直接使用this.$routers,但是在网上看了很多例子,实验无果。

因为此时的this我打印出来是undefined,所以this.$message和this.$router都不能用

关于登录失效的提示,可以使用Vue.prototype.$message,
跳转的话,可以使用router.replace(’/login’)

值得注意的是,如果你在请求失败的代码中写了this.$message.error(‘错误信息’),那么 return response.data也会返回一个打印的错误,此时不会显示Vue.prototype.$message.error(‘登录已过期,请重新登录’),优先显示请求失败的代码中写了this.$message.error(‘错误信息’)

所以要写if else判断,当后端返回状态码是4002(tooken有误)时,不返回后端响应的数据,只触发 Vue.prototype.$message.error(‘登录已过期,请重新登录’)和router.replace(’/login’)即可。

而其他情况的时候,直接返回后端相应的数据即可。

猜你喜欢

转载自blog.csdn.net/weixin_42557996/article/details/101703305
今日推荐