axios拦截器?
Posted 向往回得来
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了axios拦截器?相关的知识,希望对你有一定的参考价值。
// 引入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
})
return
config
}, error => {
loadinginstace.close()
Message.error({
message:
‘加载超时‘
})
return
Promise.reject(error)
})
// http响应拦截器
axios.interceptors.response.use(data => {
// 响应成功关闭loading
loadinginstace.close()
return
data
}, error => {
loadinginstace.close()
Message.error({
message:
‘加载失败‘
})
return
Promise.reject(error)
})
export
default
axios
设置登陆拦截
import Vue from
‘vue‘
import Router from
‘vue-router‘
Vue.use(Router)
const router =
new
Router({
routes: [
{
path:
‘/‘
,
/*
* 按需加载
*/
component: (resolve) => {
require([
‘../components/Home‘
], resolve)
}
}, {
path:
‘/record‘
,
name:
‘record‘
,
component: (resolve) => {
require([
‘../components/Record‘
], resolve)
}
}, {
path:
‘/Register‘
,
name:
‘Register‘
,
component: (resolve) => {
require([
‘../components/Register‘
], resolve)
}
}, {
path:
‘/Luck‘
,
name:
‘Luck‘
,
// 需要登录才能进入的页面可以增加一个meta属性
meta: {
requireAuth:
true
},
component: (resolve) => {
require([
‘../components/luck28/Luck‘
], resolve)
}
}
]
})
// 判断是否需要登录权限 以及是否登录
router.beforeEach((to, from, next) => {
if
(to.matched.some(res => res.meta.requireAuth)) {
// 判断是否需要登录权限
if
(localStorage.getItem(
‘username‘
)) {
// 判断是否登录
next()
}
else
{
// 没登录则跳转到登录界面
next({
path:
‘/Register‘
,
query: {redirect: to.fullPath}
})
}
}
else
{
next()
}
})
export
default
router
以上是关于axios拦截器?的主要内容,如果未能解决你的问题,请参考以下文章