vue2 对路由控制以及axios请求响应的封装

router/index.js

import Vue from 'vue'
import Router from 'vue-router'
Vue.use(Router)

import Wregister from '@/views/pc/page/login/Wregister.vue'
import Wlogin from '@/views/pc/page/login/login.vue'

// 解决ElementUI导航栏中的vue-router在3.0版本以上重复点菜单报错问题
const originalPush = Router.prototype.push
Router.prototype.push = function push (location) {
  return originalPush.call(this, location).catch(err => err)
}

const whiteList = ['Wlogin'] // 免登录白名单
const defaultRoutePath = '/Windex' //首页

const routes = [
    {
        path: '/Whome',
        component: () =>
            import('../components/common/Home.vue'),
        name: 'Whome',
        children: [{
            path: '/Windex',
            name: 'Windex',
            component: () =>
                import('../views/pc/page/index/WIndex.vue'),
            meta: {
                title: '系统首页'
            }
        }
        // 404界面
        {
            path: '/W404',
            name: 'W404',
            component: () =>
                import('../views/pc/page/404.vue'),
            meta: {
                title: '404'
            }
        },
        // 权限验证界面
        {
            path: '/W403',
            name: 'W403',
            component: () =>
                import('../views/pc/page/403.vue'),
            meta: {
                title: '403'
            }
        },
        // 500
        {
            path: '/W500',
            name: 'W500',
            component: () =>
                import('../views/pc/page/500.vue'),
            meta: {
                title: '500'
            }
        }
        ]
    },
    {
        path: '/Wregister',
        name: 'Wregister',
        component: Wregister
    },
    {
        path: '/',
        name: 'Wlogin',
        component: Wlogin
    },
    {
        path: '/500',
        name: '500',
        component: () =>
            import('../echarts/demo.vue')
    }

]
const router = new Router({
    mode: 'history',
    routes: routes
})
// 路由信息拦截
router.beforeEach((to, from, next) => {
    // NProgress.start() // start progress bar
    let token = localStorage.getItem('token');
    /* has token */
    if (token) {
        if (to.path === '/Wlogin') {
            next({ path: defaultRoutePath })
            // NProgress.done()
        } else {
            next()
        }
    } else {
        if (whiteList.includes(to.name)) {
            // 在免登录白名单,直接进入
            next()
        } else {
            Vue.prototype.$message({
                message: '登录信息失效,请重新登录',
                type: 'error'
            })
            next({ path: '/', query: { redirect: to.fullPath } })
        }
    }
    if (to.matched.length === 0) {  //匹配前往的路由不存在
        from.name ? next({
            name: from.name
        }) : next('/W404'); //判断此跳转路由的来源路由是否存在,存在的情况跳转到来源路由,否则跳转到404页面
    }
})
export default router

axios的request.js封装

import axios from 'axios';
import Vue from 'vue'
import { Loading } from 'element-ui';
import router from '../router'

// 定义 loading 
let loading
// loading开始 方法
function startLoading() {
    // element-ui loading 服务调用方式  
    loading = Loading.service({
        lock: true,
        text: '拼命加载中...',
        spinner: 'el-icon-loading',  // 自定义图标
        background: 'rgba(0, 0, 0, 0.1)'
    })
}
// loading结束 方法
function endLoading() {
    loading.close()
}


const service = axios.create({
    // timeout: 10000,
    // retry: 3
});
const err = (error) => {
    if (error.toString().indexOf("Network Error") != -1) {
        Vue.prototype.$message({
            message: '后端服务未启动',
            type: 'error'
        })
        router.push('/');
    }
    endLoading();
    if (error.response) {
        const data = error.response.data
        const token = localStorage.getItem('token')

        if (error.response.status === 403) {
            console.log('服务器403啦,要重新登录!')
            Vue.prototype.$message({
                message: data.message,
                type: 'error'
            })
            router.push('/');
        }
        if (error.response.status === 500) {
            console.log('服务器内部错误!')
            router.push('/W500');

        }
        if (error.response.status === 401 && !(data.result && data.result.isLogin)) {
            Vue.prototype.$message({
                message: '自主校验失败',
                type: 'error'
            })
            if (token) {
                store.dispatch('Logout').then(() => {
                    setTimeout(() => {
                        window.location.reload()
                    }, 1500)
                })
            }
        }
    }
    return Promise.reject(error)
}
// 添加请求拦截器
service.interceptors.request.use(
    (config) => {
        const token = localStorage.getItem('token')
        if (token) {
            token ? config.headers.token = token : null;
        }
        // 请求显示loading 效果
        startLoading();

        return config
    }, err
)

// 添加响应拦截器
service.interceptors.response.use(
    (resp) => {
        endLoading();
        if (resp.request.responseType === 'blob') {
            return resp
        }
        let response = resp.data
        if (response.code === 10404 || response.code === 10403) {
            Vue.prototype.$message({
                message: '登录过期,请重新登录',
                type: 'error'
            })
            localStorage.removeItem('token')
            router.push('/');
        } 
        //  自己项目的具体code对应信息
        else if (response.code === 10199 || response.code === 10200 || response.code === 10201 || response.code === 30092 || response.code === 30070 || response.code === 30132 || response.code === 50126 || response.code === 50095 || response.code === 50178 || response.code === 50183 || response.code === 11086 || response.code === 11089 || response.code === 12137 || response.code === 12120 || response.code === 12115 || response.code === 12107 || response.code === 12101 || response.code === 12046 || response.code === 12208) {
            alert(response.error)
            return response
        } else {
            return response
        }
    }, err)


export default service;

你可能感兴趣的:(前端,vue学习笔记,vue-router,axios封装)