给axios实例设置请求头
时间: 2023-08-05 16:05:07 浏览: 188
要给axios实例设置请求头,你可以使用axios的拦截器来在每个请求中添加请求头。下面是一个示例代码:
```javascript
import axios from 'axios';
const instance = axios.create({
baseURL: 'http://example.com/api',
timeout: 5000,
});
// 添加请求拦截器
instance.interceptors.request.use(
config => {
// 在这里设置请求头
config.headers['Content-Type'] = 'application/json';
config.headers['Authorization'] = 'Bearer your_token_here';
return config;
},
error => {
return Promise.reject(error);
}
);
export default instance;
```
在上面的代码中,我们通过axios.create()方法创建了一个axios实例,并添加了一个请求拦截器。在请求拦截器中,我们可以获取到请求的配置对象config,并在其中设置请求头。
在示例中,我们设置了两个常见的请求头:Content-Type和Authorization。你可以根据实际需求进行修改和添加其他的请求头。
请替换示例中的'your_token_here'为实际的token值。这样,在每个请求中,都会自动在请求头部添加相应的请求头。
使用时,你可以像之前一样导入这个实例,并发送请求:
```javascript
import instance from './axios';
instance.get('/user/12345')
.then(response => {
console.log(response.data);
})
.catch(error => {
console.log(error);
});
```
这样发送的请求会自动携带设置的请求头。记得将示例中的'http://example.com/api'替换为你实际的API接口地址。
阅读全文
相关推荐
![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)
![](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)