不可以直接使用axios拦截器来拦截fetch请求,因为axios拦截器是基于axios库实现的。但是可以通过对fetch方法进行封装来实现类似拦截器的功能。
例如,可以封装一个包含了请求和响应拦截器功能的fetch函数:
function fetchWithInterceptors(url, options) {
let {
requestInterceptor,
responseInterceptor
} = window.axios.interceptors;
if (requestInterceptor) {
options = requestInterceptor(options);
}
return fetch(url, options)
.then((response) => {
if (responseInterceptor) {
return responseInterceptor(response);
}
return response;
})
}
这里将axios拦截器中的请求和响应拦截器拿出来,再将fetch请求作为参数传递进来进行拦截和处理。具体的使用方式如下:
window.axios.interceptors.request.use(function (config) {
// 在发出请求前做些什么
config.headers.Authorization = `Bearer ${token}`;
return config;
}, function (error) {
// 对请求错误做些什么
return Promise.reject(error);
});
window.axios.interceptors.response.use(function (response) {
// 对响应数据做些什么
return response;
}, function (error) {
// 对响应错误做些什么
return Promise.reject(error);
});
fetchWithInterceptors('https://example.com/api/data', {
method: 'GET',
}).then((response) => {
console.log(response);
}).catch((error) => {
console.error(error);
});
这样就可以使用拦截器对fetch请求进行处理了。注意,这里使用的是window.axios.interceptors,需要确保该拦截器的实例化过程已经完成。
上一篇:Axios拦截器没有返回异常对象