请求拦截添加token
时间: 2023-09-30 22:04:09 浏览: 38
在请求拦截器中添加token的方法取决于你使用的是哪种HTTP客户端,下面以Axios为例,演示如何在请求中添加token:
```javascript
import axios from 'axios';
const instance = axios.create({
baseURL: 'https://api.example.com',
});
instance.interceptors.request.use((config) => {
// 从本地存储中获取token
const token = localStorage.getItem('token');
// 如果存在token,则在请求头中添加Authorization字段
if (token) {
config.headers.Authorization = `Bearer ${token}`;
}
return config;
}, (error) => {
return Promise.reject(error);
});
export default instance;
```
上面的示例中,我们创建了一个名为`instance`的axios实例,并使用`instance.interceptors.request.use`方法注册了一个请求拦截器。这个拦截器函数接收一个`config`对象作为参数,这个对象包含了当前请求的所有信息,例如请求方法、URL、请求头、请求正文等。
在拦截器函数中,我们从本地存储中获取到了token,如果存在token,则在请求头中添加了一个`Authorization`字段,其值为`Bearer ${token}`。这样,每个发送到服务器的请求都会携带这个token,服务器就可以用它来验证用户身份。
最后,我们导出了这个带有请求拦截器的axios实例,以便在我们的应用程序中使用它发送HTTP请求。