在 javascript 中,axios 和原生的 fetch api 都用于发出 http 请求,但它们在特性、易用性和功能方面存在一些差异。详细介绍如下:
axios:
axios 简化了发出请求和处理响应。它自动解析 json 响应,使其更易于使用。
axios.get('/api/user')
.then(response => console.log(response.data))
.catch(error => console.error(error));
获取:
使用 fetch 时,需要显式处理 json 解析,这增加了一个额外的步骤。
fetch('/api/user')
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error(error));
获取:
对于 fetch,非 2xx 状态代码(如 404 或 500)不会被视为错误。您必须手动检查响应状态并在需要时抛出错误。
fetch('/api/user')
.then(response => {
if (!response.ok) throw new error('network response was not ok');
return response.json();
})
.then(data => console.log(data))
.catch(error => console.error(error));
axios:
axios 提供内置拦截器,允许您全局修改请求或处理响应,这对于添加身份验证令牌、日志记录等非常有用
axios.interceptors.request.use(config => {
config.headers['authorization'] = 'bearer token';
return config;
});
获取:
fetch 没有内置拦截器,因此如果需要此行为,您需要手动将 fetch 调用包装在自定义函数中。
axios:
axios 在发出 post 请求时自动对数据进行字符串化,并将 content-type 设置为 application/json。它还支持轻松发送 formdata 等其他格式的数据。
axios.post('/api/user', { name: 'john' });
获取:
在 fetch 中,您需要手动对数据进行字符串化并设置 post 请求的标头。
fetch('/api/user', {
method: 'post',
headers: { 'content-type': 'application/json' },
body: json.stringify({ name: 'john' })
});
axios:
axios 内置支持使用 canceltoken 取消请求。
const source = axios.canceltoken.source();
axios.get('/api/user', { canceltoken: source.token });
source.cancel('request canceled.');
获取:
使用 fetch 时,您需要使用 abortcontroller 来取消请求,这可能会更复杂一些。
const controller = new AbortController();
fetch('/api/user', { signal: controller.signal });
controller.abort();
如果您希望更好地控制您的请求,您可能会坚持使用 fetch。如果您想要简化 http 请求的东西,axios 将是更好的选择。