以退出登录接口为例
请求拦截器:做一些发送请求前的操作,比如说在请求头上携带token,处理一些错误
响应拦截器:处理接口发送后的响应数据
import axios from 'axios'
import router from '@/router'
import { MessageBox, Message } from 'element-ui'
import store from '@/store'
import { getToken } from '@/utils/auth'
// 创建axios实例
const service = axios.create({
baseURL: '/api', // url = base url + request url
// withCredentials: true, // send cookies when cross-domain requests
timeout: 5000 // 请求超时
})
// 请求拦截器
service.interceptors.request.use(
(config) => {
// 发送请求前的操作
if (store.getters.token) {
// 让每个请求携带 token
// 请根据实际情况修改
config.headers.common['Authorization'] = getToken()
return config
},
(error) => {
// 处理请求错误
console.log('请求错误', error) // for debug
return Promise.reject(error)
}
)
// 响应拦截器
service.interceptors.response.use(
/**
* If you want to get http information such as headers or status
* Please return response => response
*/
/**
* 通过自定义代码确定请求状态
* 这里只是一个例子
* 您也可以通过HTTP状态代码来判断状态
*/
(response) => {
console.log(` ~ 响应数据:${response.config.url}`, response.data)
const res = response.data
// 如果code不是200,则判断为错误。
if (res.code !== 200) {
Message({
message: res.message || 'Error',
type: 'error',
duration: 5 * 1000
})
// 50008: 非法 token; 50012: 其他客户端已经登录; 50014: Token过期;
if (res.code === 50008 || res.code === 50012 || res.code === 50014) {
// to re-login
MessageBox.confirm(
'You have been logged out, you can cancel to stay on this page, or log in again',
'Confirm logout',
{
confirmButtonText: 'Re-Login',
cancelButtonText: 'Cancel',
type: 'warning'
}
).then(() => {
store.dispatch('user/resetToken').then(() => {
location.reload()
})
})
}
return Promise.reject(new Error(res.message || 'Error'))
} else {
return res
}
},
(error) => {
const { response } = error
console.error('网络繁忙', response)
if (response) {
if (response.status == 401) {
router.push('/login')
store.dispatch('user/logout')
response.data = {
success: false,
errorMsg: '登录信息已过期,请您重新登录'
}
return response
}
return Promise.reject(
'由于网络繁忙,请求' + response.config.apiDesc + '有误,请稍后再试'
)
} else {
return Promise.reject('请求被中断')
}
}
)
import router from './router'
import store from './store'
import { Message } from 'element-ui'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import { getToken } from '@/utils/auth' // get token from cookie
import getPageTitle from '@/utils/get-page-title'
NProgress.configure({ showSpinner: false }) // NProgress Configuration
//接口白名单,这里面的页面不需要登录就可以直接访问
const whiteList = ['/login'] // no redirect whitelist
router.beforeEach(async (to, from, next) => {
// start progress bar
NProgress.start()
// set page title
document.title = getPageTitle(to.meta.title)
// 判断是否有token,确定用户是否已登录
const hasToken = getToken()
if (hasToken) {
if (to.path === '/login') {
// 如果已登录,则重定向到主页
next({ path: '/' })
NProgress.done()
} else {
const hasGetUserInfo = store.getters.name
if (hasGetUserInfo) {
next()
} else {
try {
// 获取用户信息
// await store.dispatch('user/getInfo')
next()
} catch (error) {
// remove token and go to login page to re-login
await store.dispatch('user/resetToken')
Message.error(error || 'Has Error')
next(`/login?redirect=${to.path}`)
NProgress.done()
}
}
}
} else {
/*没有token*/
if (whiteList.indexOf(to.path) !== -1) {
// 在白名单中,直接进入
next()
} else {
// 其他没有访问权限的页面被重定向到登录页面
next(`/login?redirect=${to.path}`)
NProgress.done()
}
}
})
router.afterEach(() => {
// finish progress bar
NProgress.done()
})
import request from '@/utils/request'
//退出登录
export function logout() {
return request({
url: '/typt-admin/admin/logout',
method: 'post'
})
}
其他代码自己参照项目看,贴一段
// user logout
logout({ commit, state }) {
return new Promise((resolve, reject) => {
logout(state.token)
.then(() => {
removeToken() // 删除cookie中的token
resetRouter()
commit('RESET_STATE')
resolve()
})
.catch((error) => {
reject(error)
})
})
},
methods: {
async logout() {
await this.$store.dispatch('user/logout')
this.$router.push(`/login?redirect=${this.$route.fullPath}`)
}
}