/**
* http配置
*/
import axios from ‘axios‘;
import Cookies from ‘js-cookie‘;
//http request 拦截器
axios.interceptors.request.use(
(config) => {
// console.log(‘config‘, config.url);
if (Cookies.get(‘sessionId‘) && config.url != ‘http://xxx.xxx.xxx/exit‘ && config.url != ‘http://xxx.xxx.xxx/exit‘ && config.url != ‘https://xxx.xxx.xxx/exit‘) {
let token = "token " + Cookies.get(‘sessionId‘)
config.headers.Authorization = token;
}
return config;
},
(error) => {
// console.log(‘request-error‘, error);
return Promise.reject(error);
}
);
//http response 拦截器
axios.interceptors.response.use(
(response) => {
// console.log(‘response‘, response);
return response;
},
(error) => {
//如果响应器状态码为401,跳转到登录页if (error.response.status == 401) {
router.push(‘/login‘);
}
return Promise.reject(error);
}
)
路由全局拦截
import Vue from ‘vue‘ import Router from ‘vue-router‘ import store from ‘../store‘ import login from ‘../views/login/login‘ import index from ‘../views/index/index‘ import course from ‘../views/course/course‘ import play from ‘../views/play/play‘ import playInfo from ‘../views/play/play-info‘ import managerClient from ‘./manager_client.js‘ Vue.use(Router) const routes = [{ path: ‘/login‘, name: ‘login‘, component: login, }, { path: ‘/‘, name: ‘index‘, component: index, }, { path: ‘/course‘, name: ‘course‘, component: course, }, { path: ‘/play‘, name: ‘play‘, component: play, }, { path: ‘/play-info‘, name: ‘play-info‘, component: playInfo, }, ...managerClient] const router = new Router({ mode: ‘hash‘, routes: routes }); //全局拦截器 router.beforeEach((to, from, next) => { console.log(‘to‘, to); console.log(‘from‘, from); if (to.path == ‘/controll‘ || to.path == ‘/editControll‘) {
//判断vuex是否存在 console.log(‘this.$store.state.user.isAdmin‘, store.state.user); if (store.state.user) { if (store.state.user.isAdmin) { next() } else { next(false) } } else { next(false) } } else { next() } }) export default router
首先我们要明白设置拦截器的目的是什么,当我们需要统一处理http请求和响应时我们通过设置拦截器方便处理,路由拦截可以禁止用户手动进入那些需要权限的页面