1.在定义路由时添加自定义字段
meta: {
requireAuth:
true,
},
2.使用路由定义的钩子函数
router.
beforeEach((
to,
from,
next)
=> {
if (
to.
meta.
requireAuth) {
if (
store.
state.
token) {
next();
}
else {
next({
path:
'/login',
query: {
redirect:
to.
fullPath}
})
}
}
else {
next();
}
})
3. 统一处理所有http请求和响应,使用 axios 的拦截器
// http request 拦截器
axios.
interceptors.
request.
use(
config
=> {
if (
store.
state.
token) {
config.
headers.
Authorization =
`token
${
store.
state.
token
}
`
}
return
config
},
err
=> {
return
Promise.
reject(
err)
},
)
// http response 拦截器
axios.
interceptors.
response.
use(
response
=> {
return
response
},
error
=> {
if (
error.
response) {
switch (
error.
response.
status) {
case
401:
// 401 清除token信息并跳转到登录页面
store.
commit(
types.
LOGOUT)
// 只有在当前路由不是登录页面才跳转
router.
currentRoute.
path !==
'login' &&
router.
replace({
path:
'login',
query: {
redirect:
router.
currentRoute.
path },
})
}
}
// console.log(JSON.stringify(error));//console : Error: Request failed with status code 402
return
Promise.
reject(
error.
response.
data)
},
)