在使用axios发送请求时,可以通过拦截器来自定义请求头。以下是一个示例,仅将自定义标头添加到OPTIONS请求:
import axios from 'axios';
// 创建axios实例
const instance = axios.create();
// 请求拦截器
instance.interceptors.request.use(config => {
// 如果是OPTIONS请求,则添加自定义标头
if (config.method === 'options') {
config.headers['Custom-Header'] = 'value';
}
return config;
}, error => {
return Promise.reject(error);
});
// 发送请求
instance({
method: 'options',
url: 'https://example.com/api',
}).then(response => {
console.log(response);
}).catch(error => {
console.error(error);
});
在上面的示例中,我们使用axios.create()方法创建了一个axios实例,并通过interceptors.request.use()方法添加了一个请求拦截器。在拦截器中,我们检查请求的方法是否为OPTIONS,如果是,则将自定义标头添加到请求的config.headers中。最后,我们通过实例来发送一个OPTIONS请求,并使用.then()和.catch()分别处理成功和失败的回调函数。
请注意,以上示例中的https://example.com/api仅作为示例URL,您需要根据实际情况替换为您的API的URL。