const routes = [
{
path: '/',name: '/''repository'true,// 添加该字段,表示进入这个路由是需要登录的
},component: Repository
},{
path: '/login'
router.beforeEach((to,from,next) => {
if (to.meta.requireAuth) { 判断该路由是否需要登录权限
if (store.state.token) { 通过vuex state获取当前的token是否存在
next();
}
else {
next({
path: '/login' 将跳转的路由path作为参数,登录成功后跳转到该路由
})
}
}
{
next();
}
})
http request 拦截器
axios.interceptors.request.use(
config => {
判断是否存在token,如果存在的话,则每个http header都加上token
config.headers.Authorization = `token ${store.state.token}`;
}
return config;
},err => Promise.reject(err);
});
http response 拦截器
axios.interceptors.response.use(
response => response;
},error =>if (error.response) {
switch (error.response.status) {
case 401:
返回 401 清除token信息并跳转到登录页面
store.commit(types.LOGOUT);
router.replace({
path: 'login'return Promise.reject(error.response.data) 返回接口返回的错误信息
});
/**
* http配置
*/
引入axios以及element ui中的loading和message组件
import axios from 'axios'
import { Loading,Message } from 'element-ui'
超时时间
axios.defaults.timeout = 5000
http请求拦截器
var loadinginstace
axios.interceptors.request.use(config => {
element ui Loading方法
loadinginstace = Loading.service({ fullscreen: true })
config
},1)"> {
loadinginstace.close()
Message.error({
message: '加载超时'
})
Promise.reject(error)
})
http响应拦截器
axios.interceptors.response.use(data => { 响应成功关闭loading
loadinginstace.close()
data
},1)"> {
loadinginstace.close()
Message.error({
message: '加载失败' Promise.reject(error)
})
export default axios
Vue.prototype.$http.interceptors.response.use()