vue 处理后端返回token
调用后端获取token并保持
handleLogin(){
this.loginAuthData.params = this.loginData
this.loginAuthData.params.uuid = this.imageCodeId
console.log(this.loginAuthData)
httpClient.post(this.loginAuthData.url,this.loginAuthData.params).then(
res =>{
// console.log(res.data)
let token = "Bearer " + res.data.token
console.log(token)
localStorage.setItem('authorization', token)
this.$router.push("/home")
}
).catch(
res => {
this.$message.error({
message: res.msg
})
}
)
}
添加拦截器
import router from '@/router';
import axios from 'axios';
//新建个axios对象
const httpClient = axios.create({
validateStatus(status) {
return status >= 200 && status < 504 // 设置默认的合法的状态
},
timeout: 10000 //超时时间10秒
});
httpClient.defaults.retry = 3 // 请求重试次数
httpClient.defaults.retryDelay = 1000 // 请求重试时间间隔
httpClient.defaults.shouldRetry = true // 是否重试
//添加请求拦截器
httpClient.interceptors.request.use(
config => {
//添加header
config.headers['Content-Type'] = 'application/json'
config.headers['Accept-Language'] = 'zh-CN'
config.headers['Authorization'] = localStorage.getItem('authorization') // 可以全局设置接口请求header中带token
if (config.method === 'post') {
if (!config.data) { // 没有参数时,config.data为null,需要转下类型
config.data = {}
}
// config.data = JSON.stringify(config.data) // qs序列化参数
}
return config
},
err => {
//Promise.reject()方法返回一个带有拒绝原因的Promise对象,在F12的console中显示报错
Promise.reject(err)
}
);
//添加响应拦截器
httpClient.interceptors.response.use(
response => {
if (response.status !== 200) {
return Promise.reject(response.data)
} else {
return response.data
}
},
err => {
if (err.response && err.response.status === 401){
localStorage.removeItem('authorization')
return router.push("/login")
}
return Promise.reject(err)
}
);
export default httpClient;
请求判断是否有token,index.js
//判断token
router.beforeEach((to,from,next) =>{
if (to.path === '/login'){
next()
}else{
let token = localStorage.getItem('authorization')
if (token === null || token === ''){
next('/login')
}else{
next()
}
}
})