要去掉Axios的异步功能,可以使用原生的Fetch API来替代Axios。以下是一个使用Fetch API的示例代码:
function fetchData(url) {
return fetch(url)
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.json();
})
.catch(error => {
console.error('Error:', error);
});
}
// 调用示例
fetchData('https://api.example.com/data')
.then(data => {
console.log('Data:', data);
});
在上面的示例中,fetchData函数通过使用Fetch API来发送一个GET请求,并返回一个Promise对象。如果请求成功,它会将响应转换为JSON格式,并通过resolve方法将数据传递给下一个.then块。如果请求失败,它会抛出一个错误,并通过reject方法将错误传递给下一个.catch块。
注意:Fetch API在旧版本的浏览器中可能不被支持,你可以使用polyfill库来提供对Fetch API的支持,比如使用isomorphic-fetch或whatwg-fetch。