我使用Fetch调用web服务,但我可以在Axios的帮助下做同样的事情。现在我很困惑。我应该选择Axios还是Fetch?
当前回答
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和错误处理。
请参考这个
其他回答
axios的好处:
变形:允许在发出请求之前或在收到响应之后对数据进行转换 拦截器:允许您完全更改请求或响应(包括头)。也执行异步操作之前提出请求或承诺解决之前 内置XSRF保护
axios相对于fetch的优点
对于fetch,我们需要处理两个承诺。使用axios,我们可以直接访问响应对象数据属性中的JSON结果。
Axios是一个独立的第三方包,可以使用NPM轻松安装到React项目中。
你提到的另一个选项是fetch函数。与Axios不同,fetch()内置于大多数现代浏览器中。使用fetch,您不需要安装第三方包。
所以这取决于你,你可以使用fetch(),如果你不知道你在做什么,可能会搞砸,或者只是使用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和错误处理。
请参考这个
它们是HTTP请求库…
我最终也产生了同样的怀疑,但这篇文章中的表格让我选择了同构取回。它是fetch,但适用于NodeJS。
http://andrewhfarmer.com/ajax-libraries/
上面的链接失效了 同样的表格在这里:https://www.javascriptstuff.com/ajax-libraries/
或者在这里:
推荐文章
- Next.js React应用中没有定义Window
- 如何重置笑话模拟函数调用计数之前,每次测试
- 如何强制一个功能React组件渲染?
- 在javascript中从平面数组构建树数组
- 将Dropzone.js与其他字段集成到现有的HTML表单中
- 如何在AngularJS中观察路由变化?
- JavaScript DOM删除元素
- 将dd-mm-yyyy字符串转换为日期
- Javascript复选框onChange
- Javascript函数前导bang !语法
- 如何在页面上遍历所有DOM元素?
- 在JS/jQuery中触发按键/按键/按键事件?
- 如何每5秒重新加载页面?
- 避免浏览器弹出窗口拦截器
- getJSON调用中的错误处理