vue中axios请求带token

在vue中我们是通过axios来请求数据

和ajax很类似

在目前前后端分离的开发模式中,我们通常用token来实现认证

以下为axios请求自带token

```
import axios from 'axios'
import qs from 'Qs'
```

```
axios
.get('/api/v1/delete?id='+row.id,
{
headers:{
Authorization:"Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9"
}
}
)
.then(response => {
console.log(response);
})
.catch(function (error) { // 请求失败处理
console.log(error);
});
```

以下为post方式带token

```
let data = {"user_name":this.param.username,'password':this.param.password};
axios
.post('/api/v1/admin/login_by_user',qs.stringify(data),
{
headers:{
Authorization:"Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9"
}
}
)
.then(response => {
console.log(response.data.status);
if(response.data.status == 'success'){
this.$message.success('登录成功');
localStorage.setItem('ms_username', this.param.username);
localStorage.setItem('Authorization', 'Bearer '+response.data.data.code);
this.$router.push('/');
}else{
this.$message.error('请输入账号和密码');
localStorage.removeItem('Authorization');
console.log('error submit!!');
return false;
}
})
.catch(function (error) { // 请求失败处理
console.log(error);
});
```

    A+
发布日期:2022年11月19日  所属分类:未分类

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: