javascript 是否有任何理由使用 axios 代替 ES6 fetch
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/50277504/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Is there any reasons to use axios instead ES6 fetch
提问by Sasha Kos
Studied the documentation of axios and of ES6 fetch I found than both are quite similar and have experienced a strong influence of $.ajax and its shorthands.
研究了 axios 和 ES6 fetch 的文档,我发现两者都非常相似,并且都受到了 $.ajax 及其速记的强烈影响。
Main advantage of axios is browser support.
axios 的主要优点是浏览器支持。
So am I right that if I use babel-polyfill - there is no reasons to use axios?
那么我是否正确,如果我使用 babel-polyfill - 没有理由使用 axios?
回答by mpontus
A few reasons for using Axios over Fetch:
使用 Axios 而不是 Fetch 的几个原因:
- Ability to monitor request progress
- 能够监控请求进度
This is more of a question between XMLHttpRequest (which powers axios) or Fetch API.
这更多是 XMLHttpRequest(为 axios 提供支持)或 Fetch API 之间的问题。
Fetch API currently does not provide any way to get notified of the request progress, a feature which powers feedback mechanism for large file uploads for example.
Fetch API 目前不提供任何方式来获得请求进度的通知,例如为大文件上传提供反馈机制的功能。
Axios, on the other hand, has this functionality built in:
另一方面,Axios 内置了以下功能:
axios.post('/api', data, {
onUploadProgress: ({ total, loaded }) => {
// update progress
}),
})
- Error handling
- 错误处理
When your backend returns 500 Internal Server Errorresponse code, fetchwill not treat it any different from 200 OK.
当您的后端返回500 Internal Server Error响应代码时,fetch不会将其与200 OK.
This is an inconvenience in most cases since all your previous assumptions of what a response would look like are no longer valid.
在大多数情况下,这会带来不便,因为您之前对响应外观的所有假设都不再有效。
Most often, when receiving an erroneous response from the server you'd want to abort the processing pipeline as soon as possible, and switch to an error handling case.
大多数情况下,当收到来自服务器的错误响应时,您希望尽快中止处理管道,并切换到错误处理情况。
fetch(url)
.then(reponse => {
if (!(status >= 200 && status < 300)) {
return Promise.reject(new Error("Invalid response status"));
}
return response;
})
.then(response => response.json())
.then(/* normal processing */)
.catch(/* error handling */);
This is not hard to accomplish, but you'd probably want to capture this logic under some abstraction to avoid repetition, and this brings us one step closer to Web API abstraction which is Axios.
这并不难实现,但您可能希望在某种抽象下捕获此逻辑以避免重复,这使我们更接近 Axios 的 Web API 抽象。
Axios does a sane thing and rejects the promise if the response returns erroneous status. This behavior is customizable as are most of the things with axios.
如果响应返回错误状态,Axios 会做一件理智的事情并拒绝承诺。这种行为是可定制的,因为 axios 的大多数事情也是如此。
- Testing
- 测试
Axios has moxios, fetch has fetch-mock.
Axios 有moxios, fetch 有fetch-mock。
Both of those libraries are great but in my experience, fetch-mockrequired additional setup to get Jest to use mocked fetch over polyfilled one.
这两个库都很棒,但根据我的经验,fetch-mock需要额外的设置才能让 Jest 使用模拟 fetch 而不是 polyfill 的。
I also like that moxios.wait()returns a promise which will be resolved after matching the request.
我也喜欢它moxios.wait()返回一个承诺,该承诺将在匹配请求后得到解决。
- Other features that Axios offers
- Axios 提供的其他功能
For example, you can configure an interceptor which will add api key to all request parameters, or monitor active requests to show a loading screen.
例如,您可以配置一个拦截器,它将 api 密钥添加到所有请求参数,或监视活动请求以显示加载屏幕。
Reasons for using one option over the other may vary from actual requirements to convenience.
使用一个选项而不是另一个选项的原因可能因实际要求和方便而异。
If you need to monitor progress, use Axios (or XMLHttpRequest).
如果您需要监控进度,请使用 Axios(或 XMLHttpRequest)。
If you are writing a service worker, use Fetch.
如果您正在编写 Service Worker,请使用 Fetch。
Otherwise, use what's more convenient to you.
否则,请使用对您更方便的方法。
回答by Karen Grigoryan
This:
这:
fetch('https://jsonplaceholder.typicode.com/posts', {
method: 'POST',
body: JSON.stringify({
title,
body
})
}).then((res) => {
if (res.ok) {
return res.json()
}
throw new Error(res.responseText);
})
.then((data) => console.log(data))
.catch((err) => console.log(err))
can essentially be expressed by axios with this:
基本上可以由 axios 表示为:
axios.post('https://jsonplaceholder.typicode.com/posts', {
title,
body
}).then((data) => console.log(data))
.catch((err) => console.log(err))
So in essence:
所以本质上:
- No need to do
res.json(),res.text()etc - No need to handle
res.okin order to catch non 200 status errors in actual promisecatchhandler. - No need to stringify payload, it's handled by axios by default.
- 没有必要做
res.json(),res.text()等 - 无需处理
res.ok以在实际承诺catch处理程序中捕获非 200 状态错误。 - 无需对有效负载进行字符串化,默认情况下由 axios 处理。
Overall axiosprovides a more higher level and simple api to work with requests.
总体上axios提供了更高级别和更简单的 api 来处理请求。
回答by Meghan
Axios is an NPM library and therefore works on both Node.js and the browser. fetchis a Web API and is not available to Node. Conversely, Node.js has the httpmodule and does not have the Fetch API. It also simplifies passing data and handling different types of HTTP Requests
Axios 是一个 NPM 库,因此适用于 Node.js 和浏览器。fetch是一个 Web API,不适用于 Node。相反,Node.js 有http模块,没有 Fetch API。它还简化了传递数据和处理不同类型的 HTTP 请求

