One of the fundamental tasks of any web application is to communicate with servers through the HTTP protocol. This can be easily achieved using Fetch or Axios.
The Fetch API is built-in most modern browsers and provides a fetch() method defined on the window object, while Axios is a specific 3rd party Javascript library you must install manually.
Which method do you usually use and do you think adding a library (around 4.4KB gzip) is worth it for the extra features it brings?
Top comments (28)
axiosintegrates better with TypeScript interfaces, however,fetch(and well asnode-fetch) has much more predictable output.Also,
fetchcan be attachedAbortController. I would be interested in a library built on topfetch.I know there are superagent and ky, but I never really tried.
What about?
Now
datais an array of objectsFruitActually, it's just a fake typing.
It depends on the "real" data, whether it gets
JSON.parse()or not.jQuery.ajax()π€¦
That legendary function π
been there, done that ππ
I prefer
axios's API and alsofetchdoesn't throw an error when we get a non 200 response from the backend except for Network errors. Which is why I use redaxios, the best of both worlds.+1
My opinion is to use axios, because in some cases like if we have to show the progress of our request then it will be very difficult to handle this using fetch method but axios have a good managed function for that case.
Also axios provides good documentation for the function and there use.
$.getJSON()$.getScript()Don't forget
$(selector).load(uri).All of these are better than my first AJAX program: I didn't know JavaScript has closures, so that every
XMLHttpRequestobject is a global variable.It's 2006, when everyone was using IE6, I just read a book about AJAX, I haven't heard about Prototype.js, and jQuery existed for less than a year.
Axios.
API things like,
dataobject which I guess good security practice as well.axios.create.More things.
Also, works really well with TypeScript which other user has mentioned.
I use both, but mostly just stick with
fetchandnode-fetchπMost old browser will not understand fetch API and that is where, axios shines. Axios accommodates fetch API. However i think fetch API makes code look neater and a Lil bit synchronous. If I want compatibility, I'll pick axios else its fetch.
Fair enough π
If the application needs to be light and have only a few http calls, then I would generally go for either
fetchorxmlHTTPRequest.For applications that are dependent on a lot of HTTP calls, then I think
axiosis the best approach and its easy to get away with setup.fetchis fine. I don't mind the 'doubleawait' Usually, I move 'api' functionality to its own module/file anyway, so I am not typing it more than once.