我使用Fetch调用web服务,但我可以在Axios的帮助下做同样的事情。现在我很困惑。我应该选择Axios还是Fetch?


当前回答

对于fetch,我们需要处理两个承诺。使用axios,我们可以直接访问响应对象数据属性中的JSON结果。

其他回答

Axios是一个基于承诺的HTTP客户端库,而Fetch是一个用于发出API请求的javascript API。

主要区别是浏览器支持:Axios支持包括IE在内的所有浏览器,而Fetch只支持最新的浏览器,IE不支持。

参考链接:https://github.com/axios/axios浏览器支持

https://caniuse.com/fetch

与获取API相比,Axios具有更好的错误处理。Axios可以抛出400到500个范围的状态代码错误,而在fetch API中,您需要手动处理这些错误。 更多信息请访问:https://bariablogger.in/f/axios-vs-fetch-react

它们是HTTP请求库…

我最终也产生了同样的怀疑,但这篇文章中的表格让我选择了同构取回。它是fetch,但适用于NodeJS。

http://andrewhfarmer.com/ajax-libraries/


上面的链接失效了 同样的表格在这里:https://www.javascriptstuff.com/ajax-libraries/

或者在这里:

根据mzabriskie在GitHub上的说法:

总的来说,它们非常相似。axios的一些好处: 变形:允许在发出请求之前或在接收到响应之后对数据进行转换 拦截器:允许您完全更改请求或响应(包括头)。另外,在请求被发送之前执行异步操作 在承诺解决之前 内置XSRF保护

请检查浏览器支持Axios

我认为您应该使用axios。

Fetch API, need to deal with two promises to get the response data in JSON Object property. While axios result into JSON object. Also error handling is different in fetch, as it does not handle server side error in the catch block, the Promise returned from fetch() won’t reject on HTTP error status even if the response is an HTTP 404 or 500. Instead, it will resolve normally (with ok status set to false), and it will only reject on network failure or if anything prevented the request from completing. While in axios you can catch all error in catch block.

我会说更好的使用axios,直接处理拦截器,头配置,设置cookie和错误处理。

请参考这个

fetch API和axios API之间还有一个主要区别

在使用service worker时,只有当您想拦截HTTP请求时才必须使用fetch API 当使用service worker在PWA中执行缓存时,如果你使用axios API(它只适用于fetch API),你将无法缓存。