主题
API 对比与语法差异
在前端开发中,Axios 与 Fetch 都是常用的 HTTP 请求工具,但在使用方式和功能上存在差异。
一、基本语法对比
Axios
js
axios.get('/api/data', { params: { id: 1 } })
.then(res => console.log(res.data))
.catch(err => console.error(err));Fetch
js
fetch('/api/data?id=1')
.then(res => res.json())
.then(data => console.log(data))
.catch(err => console.error(err));二、请求参数传递
- Axios 使用
params传递 GET 参数,data传递 POST 数据。 - Fetch GET 参数需手动拼接 URL,POST 数据需使用
body。
三、默认处理与拦截器
- Axios 默认自动转换 JSON 数据,并支持请求/响应拦截器。
- Fetch 不提供拦截器,需要手动封装,且需调用
res.json()解析响应。
四、错误处理机制
- Axios 对 HTTP 状态码非 2xx 自动抛错。
- Fetch 默认不抛错,需手动判断
res.ok。
js
fetch('/api/data')
.then(res => {
if (!res.ok) throw new Error('Network response was not ok');
return res.json();
})
.catch(err => console.error(err));五、跨域与请求配置
- Axios 可以直接设置
withCredentials、自定义 headers。 - Fetch 需要配置
credentials: 'include',某些浏览器对跨域请求限制更多。
六、总结
| 特性 | Axios | Fetch |
|---|---|---|
| 参数传递 | params / data | URL / body |
| JSON 自动转换 | ✅ | ❌ 需手动 |
| 请求拦截器 | ✅ | ❌ 需手动封装 |
| 错误处理 | HTTP 非 2xx 自动抛错 | 需手动判断 res.ok |
| 跨域支持 | ✅ | ✅ 但需 credentials |
Axios 提供了更丰富的功能和更简洁的 API,而 Fetch 为原生标准,适合轻量请求。选择时可根据项目复杂度和团队习惯决定。