我使用Fetch调用web服务,但我可以在Axios的帮助下做同样的事情。现在我很困惑。我应该选择Axios还是Fetch?
当前回答
对于fetch,我们需要处理两个承诺。使用axios,我们可以直接访问响应对象数据属性中的JSON结果。
其他回答
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和错误处理。
请参考这个
除了……我在测试中使用了各种lib,并注意到它们对4xx请求的不同处理。在这种情况下,我的测试返回一个json对象,响应为400。这是3个流行的libs处理响应的方式:
// request-promise-native
const body = request({ url: url, json: true })
const res = await t.throws(body);
console.log(res.error)
// node-fetch
const body = await fetch(url)
console.log(await body.json())
// Axios
const body = axios.get(url)
const res = await t.throws(body);
console.log(res.response.data)
有趣的是,request-promise-native和axios在4xx响应上抛出,而节点获取则不会抛出。fetch还使用了json解析的promise。
对于fetch,我们需要处理两个承诺。使用axios,我们可以直接访问响应对象数据属性中的JSON结果。
Axios是一个独立的第三方包,可以使用NPM轻松安装到React项目中。
你提到的另一个选项是fetch函数。与Axios不同,fetch()内置于大多数现代浏览器中。使用fetch,您不需要安装第三方包。
所以这取决于你,你可以使用fetch(),如果你不知道你在做什么,可能会搞砸,或者只是使用Axios,在我看来更直接。
fetch API和axios API之间还有一个主要区别
在使用service worker时,只有当您想拦截HTTP请求时才必须使用fetch API 当使用service worker在PWA中执行缓存时,如果你使用axios API(它只适用于fetch API),你将无法缓存。