1. 针对单个请求设置请求头
在发起请求时,通过 headers
配置项设置:
import axios from 'axios';
// GET 请求
axios.get('/api/data', {
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer token123',
'Custom-Header': 'custom-value'
}
})
.then(response => {
console.log(response.data);
})
.catch(error => {
console.error(error);
});
// POST 请求
axios.post('/api/submit',
{ data: 'test' },
{
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Authorization': 'Bearer token123'
}
}
)
.then(response => {
console.log(response.data);
})
.catch(error => {
console.error(error);
});
2. 全局设置默认请求头
如果多个请求需要使用相同的请求头,可以设置全局默认值:
import axios from 'axios';
// 设置全局默认请求头
axios.defaults.headers.common['Authorization'] = 'Bearer token123';
axios.defaults.headers.post['Content-Type'] = 'application/json';
axios.defaults.headers.get['Accept'] = 'application/json';
// 之后的请求会自动带上这些头信息
axios.get('/api/data')
.then(response => {
console.log(response.data);
});
3. 使用拦截器设置请求头
拦截器可以在请求发送前动态设置请求头,适合需要根据条件动态修改的场景:
import axios from 'axios';
// 创建 axios 实例
const instance = axios.create({
baseURL: '/api'
});
// 请求拦截器
instance.interceptors.request.use(
config => {
// 在发送请求前设置请求头
const token = localStorage.getItem('token');
if (token) {
config.headers['Authorization'] = `Bearer ${token}`;
}
config.headers['Content-Type'] = 'application/json';
return config;
},
error => {
return Promise.reject(error);
}
);
// 使用实例发送请求
instance.get('/data')
.then(response => {
console.log(response.data);
});
常见的请求头设置包括:
Content-Type
:指定请求体的格式,如application/json
、application/x-www-form-urlencoded
等Authorization
:用于身份验证,通常是Bearer token
形式Accept
:指定期望的响应数据格式