Axios和Fetch是前端网络请求核心工具,Axios支持拦截器、自动JSON转换和请求取消,适合复杂项目;Fetch为浏览器原生API,轻量且支持流处理,适用于简单场景。通过自定义实例、封装函数、统一错误处理及使用AbortController取消请求,可提升代码可维护性和健壮性。两者可根据项目需求选择或共存,关键在于规范统一。

在现代前端开发中,网络请求是与后端交互的核心手段。Axios 和 Fetch API 是目前最常用的两种方式。它们各有优势,掌握其高级用法能显著提升代码的可维护性和健壮性。
1. Axios 高级配置与拦截器
Axios 是一个基于 Promise 的 HTTP 客户端,支持浏览器和 Node.js,提供了丰富的配置选项。
自定义实例:可以创建独立的 Axios 实例,设置基础 URL、超时时间、请求头等。
const apiClient = axios.create({
baseURL: 'https://api.example.com',
timeout: 5000,
headers: { 'Content-Type': 'application/json' }
});
这样所有通过 apiClient 发出的请求都会自动携带这些配置。
立即学习“Java免费学习笔记(深入)”;
请求与响应拦截器:可用于统一处理认证、日志、错误提示等。
// 请求拦截器
apiClient.interceptors.request.use(config => {
const token = localStorage.getItem('token');
if (token) {
config.headers.Authorization = `Bearer ${token}`;
}
return config;
});
// 响应拦截器
apiClient.interceptors.response.use(
response => response,
error => {
if (error.response?.status === 401) {
// 处理未授权
localStorage.removeItem('token');
window.location.href = '/login';
}
return Promise.reject(error);
}
);
拦截器极大简化了全局逻辑处理,避免重复代码。
2. Fetch API 高级用法与封装
Fetch 是浏览器原生提供的 API,无需引入额外库,但默认不发送 Cookie,且不会 reject HTTP 错误状态码。
手动处理响应状态:需检查 ok 属性或 status 来判断请求是否成功。
fetch('/api/user', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(data),
credentials: 'include' // 携带 Cookie
})
.then(res => {
if (!res.ok) throw new Error(`HTTP error! status: ${res.status}`);
return res.json();
})
.then(data => console.log(data))
.catch(err => console.error('Fetch error:', err));
封装 Fetch 提高复用性:可以封装通用逻辑,如自动解析 JSON、统一错误处理。
async function request(url, options = {}) {
const config = {
...options,
headers: {
'Content-Type': 'application/json',
...options.headers
}
};
const res = await fetch(url, config);
if (!res.ok) {
const errorData = await res.json().catch(() => ({}));
throw new Error(errorData.message || res.statusText);
}
return res.json();
}
使用封装后的函数更简洁:
request('/api/profile', { method: 'GET' })
.then(data => console.log(data))
.catch(err => alert(err.message));
3. 错误处理与取消请求
无论是 Axios 还是 Fetch,合理的错误处理和请求取消机制对用户体验至关重要。
Axios 支持 CancelToken(旧)或 AbortController(新)取消请求:
const controller = new AbortController();
apiClient.get('/search', {
params: { q: 'query' },
signal: controller.signal
})
.then(res => console.log(res.data))
.catch(thrown => {
if (axios.isCancel(thrown)) {
console.log('Request canceled', thrown.message);
}
});
// 取消请求
controller.abort();
Fetch 原生支持 AbortController:适合防止重复请求或页面切换时清理。
const controller = new AbortController();
fetch('/data', { signal: controller.signal })
.catch(e => {
if (e.name === 'AbortError') {
console.log('Fetch aborted');
}
});
// 手动取消
controller.abort();
4. 对比与选型建议
Axios 和 Fetch 各有适用场景。
- Axios 自动转换 JSON,支持拦截器,兼容性好,适合复杂项目。
- Fetch 更轻量,原生支持流式处理,适合简单场景或追求零依赖的项目。
- 若需上传进度监听,Axios 提供
onUploadProgress 回调,Fetch 目前无法直接实现。
- Fetch 在处理大文件或流数据时更具潜力,可通过
response.body 获取 ReadableStream。
实际开发中,可根据团队习惯、项目规模和功能需求选择。也可以共存,关键在于统一规范。
基本上就这些,掌握这些高级技巧能让网络请求更可控、更安全、更易维护。
以上就是JavaScript网络请求_Axios与Fetch API高级用法的详细内容,更多请关注php中文网其它相关文章!