要在使用axios发送请求时包含API密钥,可以通过在axios.create方法中配置一个请求拦截器来实现。下面是一个示例代码:
import axios from 'axios';
// 创建axios实例
const instance = axios.create({
baseURL: 'https://api.example.com',
timeout: 1000,
});
// 请求拦截器
instance.interceptors.request.use((config) => {
// 在请求发送之前,将API密钥添加到请求的params对象中
config.params = {
...config.params,
API_KEY: 'your_api_key_here',
};
return config;
}, (error) => {
return Promise.reject(error);
});
// 发送请求
instance.get('/endpoint', {
params: {
param1: 'value1',
param2: 'value2',
},
})
.then((response) => {
// 处理响应数据
console.log(response.data);
})
.catch((error) => {
// 处理错误
console.log(error);
});
在上述示例中,我们使用axios.create方法创建了一个axios实例,并配置了一个请求拦截器。在请求拦截器中,我们将API密钥添加到请求的params对象中。然后,我们可以使用这个axios实例发送请求,并在请求的params对象中包含其他参数。
请注意,上述示例中的API密钥是一个示例值,你需要将其替换为你自己的API密钥。另外,你还可以根据需要进行其他的配置,比如设置请求头或处理错误等。