vue项目中遇到的登录超时
项目中使用cookie作为用户是否登录的唯一标识,在auth.js中分别对cookie的存储、获取、删除作了封装。
我将登录超时功能写在了request.js中,在全局封装的axios请求返回中加入判断是否登录超时的操作,若登录超时,需要清除token,重新加载当前页面,再通过路由守卫拦截,从而跳转到登录页;否则无法继续获取数据。
request.js代码如下:
1 import axios from 'axios' 2 import { Dialog, Toast } from 'vant' 3 import { removeToken } from "@/utils/auth"; 4 5 // create an axios instance 6 const service = axios.create({ 7 baseURL: '/api', // url = base url + request url 8 // withCredentials: true, // send cookies when cross-domain requests 9 timeout: 5000 // request timeout 10 }) 11 12 // request interceptor 13 // service.interceptors.request.use( 14 // config => { 15 // // do something before request is sent 16 17 // if (store.getters.token) { 18 // // let each request carry token 19 // // ['X-Token'] is a custom headers key 20 // // please modify it according to the actual situation 21 // config.headers['X-Token'] = getToken() 22 // } 23 // return config 24 // }, 25 // error => { 26 // // do something with request error 27 // console.log(error) // for debug 28 // return Promise.reject(error) 29 // } 30 // ) 31 32 // response interceptor 33 service.interceptors.response.use( 34 /** 35 * If you want to get http information such as headers or status 36 * Please return response => response 37 */ 38 39 /** 40 * Determine the request status by custom code 41 * Here is just an example 42 * You can also judge the status by HTTP Status Code 43 */ 44 response => { 45 const res = response.data 46 47 // if the custom code is not 20000, it is judged as an error. 48 if (res.code !== 200) { 49 console.log(res.message) 50 Toast.fail(res.message) 51 52 // 登录超时 53 if (res.code === 401) { 54 // to re-login 55 Dialog.confirm({ 56 message: '您已登录超时,请重新登录', 57 theme: 'round-button', //圆形按钮 58 showCancelButton:false, //是否展示取消功能 59 confirmButtonColor: '#19B0AE' //确认按钮颜色 60 }).then(() => { 64 // 清除cookie,并刷新当前页面 65 // 刷新后,由于路由拦截,所以跳转到登录页 66 removeToken() 67 location.reload() 68 }) 69 } 70 return res 72 } else { 73 return res 74 } 75 }, 76 error => { 77 console.log('err' + error) // for debug 78 Toast.fail(error.message) 84 return Promise.reject(error) 85 } 86 ) 87 88 export default service