在现代Web开发中,数据交互是必不可少的环节。Fetch API和Axios是两种常用的HTTP客户端工具,用于在浏览器和Node.js环境中发起HTTP请求。下面我们来详细探讨它们的区别、联系、优缺点以及使用上的差异。
Fetch API和Axios的主要目的都是发起HTTP请求,实现客户端与服务器之间的数据交互。它们都支持常见的HTTP方法,如GET、POST、PUT、DELETE等,并且可以处理各种类型的响应数据,如JSON、文本、二进制数据等。
response.json()
方法。fetch('https://api.example.com/data')
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error(error));
axios.get('https://api.example.com/data')
.then(response => console.log(response.data))
.catch(error => console.error(error));
// 请求拦截
axios.interceptors.request.use(config => {
// 在发送请求之前做些什么
config.headers.Authorization = 'Bearer ' + token;
return config;
}, error => {
// 对请求错误做些什么
return Promise.reject(error);
});
// 响应拦截
axios.interceptors.response.use(response => {
// 对响应数据做点什么
return response;
}, error => {
// 对响应错误做点什么
return Promise.reject(error);
});
response.ok
属性来判断请求是否成功。fetch('https://api.example.com/data')
.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.get('https://api.example.com/data')
.then(response => console.log(response.data))
.catch(error => {
if (error.response) {
// 请求已发出,但服务器响应状态码不在 2xx 范围内
console.log(error.response.data);
console.log(error.response.status);
console.log(error.response.headers);
} else if (error.request) {
// 请求已发出,但没有收到响应
console.log(error.request);
} else {
// 其他错误
console.log('Error', error.message);
}
});
fetch('https://api.example.com/data', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ key: 'value' })
})
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error(error));
axios.post('https://api.example.com/data', { key: 'value' })
.then(response => console.log(response.data))
.catch(error => console.error(error));
AbortController
实现超时取消请求。const controller = new AbortController();
const signal = controller.signal;
// 设置超时时间为3000毫秒
const timeoutId = setTimeout(() => {
controller.abort();
}, 3000);
fetch('https://api.example.com/data', { signal })
.then(response => {
clearTimeout(timeoutId);
return response.json();
})
.then(data => console.log(data))
.catch(error => {
if (error.name === 'AbortError') {
console.log('请求超时被取消');
} else {
console.error(error);
}
});
CancelToken
实现超时取消请求。const CancelToken = axios.CancelToken;
const source = CancelToken.source();
// 设置超时时间为3000毫秒
const timeoutId = setTimeout(() => {
source.cancel('请求超时被取消');
}, 3000);
axios.get('https://api.example.com/data', {
cancelToken: source.token
})
.then(response => {
clearTimeout(timeoutId);
console.log(response.data);
})
.catch(error => {
if (axios.isCancel(error)) {
console.log(error.message);
} else {
console.error(error);
}
});
Fetch API和Axios各有优缺点,选择使用哪一个取决于项目的具体需求。如果项目对浏览器兼容性要求不高,且希望减少依赖,可以选择Fetch API;如果需要处理复杂的请求和响应,或者需要支持旧版本的浏览器,Axios是更好的选择。