vue获取token登录的过程:
1,访问需要登录的页面的时候,利用路由守卫跳转,输入正确的用户名密码 向后台的认证接口发送数据
2,获取token 用vuex存储 ,且存储到localstorage中,关闭页面,下次重新访问可不用登陆,直接从localstorage取值,token过期时间由后台控制
3,axios 拦截 设置接下来的接口访问带着token;当token过期返回401跳转登陆重新获取token进行登录,
废话不多说,下面直接上代码
mian.js
```javascript
export const instance = axios.create({
timeout: 20000,
validateStatus: function (status) {
return status < 500
},
headers: {
'Accept': 'application/json'
},
})
instance.interceptors.response.use(
response =>{
switch (response.status) {
case 401:
router.replace({
path:'/login',
query:{redirect:router.currentRoute.fullPath}
})
}
return response
},
error => {
return Promise.reject(error.response)
}
)
router
```javascript
import Vue from 'vue'
import Router from 'vue-router'
import Page from '@/components/Page'
import Index from '@/components/Index'
// import NotFound from "@/components/404";
import Login from "@/components/Login";
Vue.use(Router)
const router = new Router({
mode: 'history',
routes: [
{
path: '/login',
name: 'Login',
component: Login
},
{
path: '/',
redirect:'/index'
},
{
path: '/index',
name: 'Index',
component: Index,
meta: {
loginRequest:true,
requireAuth:true
}
},
{
path: '/report',
name: 'report',
component: Index,
meta: {
title: '2',
requireAuth:true
}
},
{
path: '/hospital',
name: 'hospital',
component: Index,
meta: {
title: '2',
requireAuth:true
}
},
{
path: '/:item_id/:id',
component: Page,
meta: {
title: '3',
requireAuth:true
}
},
{
path:'*',
redirect:'/index'
},
]
})
export default router
main.js
import router from './router'
router.beforeEach((to, from, next) => {
let token = window.localStorage.getItem('token')
if (to.meta.requireAuth) {
if (token) {
// store.dispatch('getUser')
next()
} else {
store.dispatch('logOut')
nex