本文代码参考链接为:https://www.cnblogs.com/zhoulifeng/p/9858605.html
视频参考链接//:https://www.bilibili.com/video/BV1gK411s7dk?from=search&seid=6866647701875999812
流程
- 1.接受到后端的数据中,存有token
- 2.保存token到localStorage,还有vuex中(包括token、用户名)
- 3.设置拦截器:
- 3.1 每次发送请求前带上token:
config.headers.Authorization = localStorage.eleToken
- 返回的请求中设置401错误处理
参考链接的代码:
import axios from 'axios'
import { Loading ,Message} from 'element-ui' //引入了element-ui框架库
import router from './router/index.js'
let loading;
function startLoading() {
loading =Loading.service({
lock: true,
text: '加载中...',
background: 'rgba(0, 0, 0, 0.7)'
});
}
function endLoading() {
loading.close()
}
// 请求拦截
axios.interceptors.request.use(config => {
startLoading()
//设置请求头
if(localStorage.eleToken) {
config.headers.Authorization = localStorage.eleToken
}
return config
}, error => {
return Promise.reject(error)
})
// 响应拦截
axios.interceptors.response.use(response => {
endLoading()
return response
}, error => {
Message.error(error.response.data)
endLoading();
//获取状态码
const {status} = error.response;
if(status === 401) {
Message.error("token失效,请重新登录");
//清除token
localStorage.removeItem('eleToken');
//重新登录
router.push('/login')
}
return Promise.reject(error)
})
export default axios;
- 4.vuex存储:包括存储用户信息【user:{}】,还有是否获取到了token【isAuthorization: Boolean】
- 5.user信息可以通过:
const decode = jwt_decode(token)
来解析token中的user信息,再存储到vuex的user:{}中
- 别的页面调用:
submitForm(formName) {
this.$refs[formName].validate((valid) => {
if (valid) {
this.$axios.post('/api/users/login',this.loginUser).then(res => {
const {token} = res.data;
//存储token
localStorage.setItem('eleToken',token)
//解析token
const decode = jwt_decode(token)
console.log(res)
// 存储到vuex
this.$store.dispatch("setAuthorization", !this.isEmpty(decode));
this.$store.dispatch("setsuer",decode)
// this.$router.push('/index')
})
}
})
},<br>//封装的验证方法
isEmpty(value) {
return (
value === undefined ||
value === null ||
(typeof value === "object" && Object.keys(value).length === 0) ||
(typeof value === "string" && value.trim().length === 0)
);
}