vue 根据接口返回的状态码判断用户登录状态并跳转登录页,登录后回到上一个页面(http拦截器)

背景:后台接口返回code==501表示用户是未登录状态,需要登录才可访问;

通过http拦截做路由跳转

 第一步:src目录下新建http.js文件,内容如下:

import Axios from 'axios'
import { Loading, Message, MessageBox } from 'element-ui'
// 超时时间
Axios.defaults.timeout = 5000
// http请求拦截器
var loadinginstace
Axios.interceptors.request.use(config => {
   // element ui Loading方法
       loadinginstace = Loading.service({ fullscreen: true })
   return config
}, error => {
   loadinginstace.close();
   Message.error({
         message: '网络不给力,请稍后再试'
     })
   return Promise.reject(error)
})
//   http响应拦截器
Axios.interceptors.response.use(data => {
    // 响应成功关闭loading
    loadinginstace.close();
    const code = data.data.code;
    if(code == 501) { //未登录
        MessageBox.alert('请先登录', '提示', {
            confirmButtonText: '确定',
            callback: action => {
                router.replace({
                    name: 'login',
                    query: {redirect: router.currentRoute.fullPath} //登录后再跳回此页面时要做的配置
                })
            }
        });
    }
    return data
}, error => {
    loadinginstace.close();
    Message.error({
         message: '网络不给力,请稍后再试'
     })
    return Promise.reject(error)
})

 2.从main.js中引入

import './http.js'

 3.登录页设置login.vue

                 if(this.$route.query.redirect){
                                this.$router.push({path: decodeURIComponent(this.$route.query.redirect)}) //跳转到原页面
                            }else{
                                this.$router.push({name: 'userIndex', query: {id: 0}});//正常登录流程进入的页面
                            }

2019-04-14更新:

tip1: 平台右上角需要显示用户名,后台在登录时返回了用户名称信息,将他放在cookie中,在头部组件中调用cookie获取用户名即可。

tip2: 刚开始把http.js的内容直接放到了main.js中,会出现以下问题:

每次页面刷新时,地址少个api