vue 封装token,请求拦截器存储token
时间: 2023-11-20 11:05:09 浏览: 112
在 Vue 中,可以使用 Axios 库进行网络请求,并使用拦截器对请求进行处理。下面是一个简单的实现示例:
1. 在 main.js 中引入 Axios 和创建一个 Axios 实例:
```js
import axios from 'axios'
const instance = axios.create({
baseURL: 'http://api.example.com',
timeout: 5000
})
Vue.prototype.$http = instance // 将 Axios 实例挂载到 Vue 原型上
```
2. 在请求拦截器中存储 token:
```js
instance.interceptors.request.use(config => {
const token = localStorage.getItem('token') // 从 localStorage 中获取 token
if (token) {
config.headers.common['Authorization'] = `Bearer ${token}` // 设置请求头中的 Authorization 字段
}
return config
}, error => {
return Promise.reject(error)
})
```
3. 在登录成功后,将 token 存储到 localStorage 中:
```js
localStorage.setItem('token', 'your_token_here')
```
通过以上步骤,我们就可以在每次请求中自动携带 token 了。需要注意的是,由于 token 存储在客户端,存在被恶意获取的风险,因此需要在后端进行严格的权限控制。
阅读全文
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20241231044930.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)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](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)