作者:cb风雨彩虹 | 来源:互联网 | 2023-10-13 12:47
http 是用
做的请求,用户每次登录之后后台都会返回一个
和
给前端。
和
都存放在localStoragel里面,在
里面设置的每次请求都会把
和
给后台去验证。
在
响应拦截器中判断服务端返回的状态码,确定用户登录是否超时;如果超时就给出提示,跳至登录页。
问题
代码
axios 请求拦截器
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
| axios.interceptors.request.use(function (config) {
const token = localStorage.getItem('token')
const uid = localStorage.getItem('uid')
if (config.method === 'post') {
let data = qs.parse(config.data)
config.data = qs.stringify({
...data,
token: token,
uid: uid
})
} else if (config.method === 'get') {
config.params = {
...config.params,
token: token,
uid: uid
}
}
return config;
}, function (error) {
return Promise.reject(error);
}) |
axios 响应拦截器
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| let preTime
axios.interceptors.response.use(function (res) {
let status = res.data.status
if (status === 9999) {
preTime = +new Date()
let nowTime = +new Date()
localStorage.removeItem('token')
localStorage.removeItem('uid')
store.dispatch(push('/login'))
if (nowTime - preTime > 600000) {
preTime = nowTime
message.error('登录超时,请重新登录')
}
}
return res
}) |