vue2请求携带token
时间: 2023-09-16 07:09:20 浏览: 341
在Vue2中发送请求并携带token可以通过以下方式实现:
1. 使用axios库发送请求
首先需要在项目中安装axios库,然后在需要发送请求的组件中引入axios库:
```
import axios from 'axios';
```
然后可以通过axios的拦截器实现在请求头中添加token:
```
// 添加请求拦截器
axios.interceptors.request.use(function (config) {
// 在发送请求之前添加token
const token = localStorage.getItem('token');
if (token) {
config.headers['Authorization'] = 'Bearer ' + token;
}
return config;
}, function (error) {
return Promise.reject(error);
});
```
在发送请求时,axios会自动将token添加到请求头中:
```
axios.get('/api/user').then(response => {
console.log(response.data);
}).catch(error => {
console.log(error);
});
```
2. 使用Vue-resource库发送请求
首先需要在项目中安装Vue-resource库,然后在需要发送请求的组件中引入Vue-resource库:
```
import VueResource from 'vue-resource';
Vue.use(VueResource);
```
然后可以在Vue-resource的拦截器中实现添加token:
```
// 添加请求拦截器
Vue.http.interceptors.push((request, next) => {
// 在发送请求之前添加token
const token = localStorage.getItem('token');
if (token) {
request.headers.set('Authorization', 'Bearer ' + token);
}
next();
});
```
在发送请求时,Vue-resource会自动将token添加到请求头中:
```
this.$http.get('/api/user').then(response => {
console.log(response.body);
}).catch(error => {
console.log(error);
});
```
阅读全文
相关推荐
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)