1、第一次登錄的時候,前端調後端的登陸接口,發送用戶名和密碼
2、後端收到請求,驗證用戶名和密碼,驗證成功,就給前端返回一個token
3、前端拿到token,將token存儲到localStorage中,並跳轉路由頁面
4、前端每次跳轉路由,就判斷 localStroage 中有無 token ,沒有就跳轉到登錄頁面,有則跳轉到對應路由頁面
調登錄接口成功,在回調函數中將token存儲到localStorage中
methods: {
submitForm(formName) {
this.$refs[formName].validate(valid => {
console.log(111)
if (valid) {
//調用登錄接口
loginApi.login(this.form.username, this.form.password).then(response => {
const resp = response.data;
console.log(resp);
if(resp.flag){
//通過token,在加上調用用戶信息接口獲取數據
loginApi.getInfo(resp.data.token).then(response=>{
const respUser = response.data;
console.log(respUser)
if(respUser.flag){
//將用戶信息存儲到本地
localStorage.setItem("adminInfo",JSON.stringify(respUser.data))
//將token存儲到本地
localStorage.setItem("adminToken",resp.data.token)
//跳轉到首頁
this.$router.push("/Layout");
}else{
this.$message({
duration : 1 * 1000,
showClose: true,
message: resp.message,
type: 'warning'
});
}
})
}else{
this.$message({
duration : 1 * 1000,
showClose: true,
message: resp.message,
type: 'warning'
});
return false;
}
})
} else {
console.log("error submit");
return false;
}
})
}
}
請求頭加token
export default {
//登錄接口
login(mobile,password){
console.log(base)
return request({
url : base+"/pro-api/user/login",
method : "post",
data : {
mobile,
password,
}
})
},
//獲取用戶信息接口
getInfo(token){
return request({
method : "get",
url : `${base}/pro-api/user/info/?token=${token}`,
})
}
}
每次請求時都會攜帶token,後臺驗證不驗證token就是後臺的問題了
設置token的回覆攔截器,對回執碼錯誤的進行操作處理
axios.interceptors.response.use(res=>{
if(res.data.res_code=== 401){
router.replace('/login');
localStorage.removeItem('token')
}
return res
})
這個根據後臺的回執碼自行更改就行