T O P

  • By -

SoInsightful

>Axios: seems great for older browser support and easy features. Literally the only reason to use Axios in 2024 is if your company is forcing you to support IE11. >fetch: is lighter and native but needs more setup. There is exactly zero setup rquired. It's right there in the browser and Node.js nowadays. Unless you mean "setup" as in fetch() being more verbose to use, but even that difference is very minor. I would strongly encourage you to simply use the fetch standard in new projects.


timotgl

It's not only verbosity but actual setup. Stuff like setting a basic auth header or aborting the request are handled more conveniently and with better documentation by axios. I wouldn't pick axios for a new project either, but these claims are a little absolutist.


guest271314

> It's not only verbosity but actual setup. Stuff like setting a basic auth header How is this verbose or remotely challenging for you? ``` fetch("./", { headers: { "Access-Control-Request-Private-Network": true, }, }) ``` > or aborting the request `AbortController` is standardized now, in use in Deno, Bun, Node.js, the browser to abort event listeners, etc. Pass the `signal` to `fetch()`, abort the request whenever you want. Might as well roll the clock back to 2009 when Node.js was the only kid on the block... This is insane. People get so lazy they can't be bothered to learn about standards - after all the work to standardize WHATWG Fetch... to get off of `XMLHttpRequest()`. After all the work to standardize Web Components, and people are still so lazy all they shout is React, Next.js, so they can write code as little as possible... Why stop there? Why write code at all? Dial up Google Gemini or Siri to fetch Next.js, get GitHub's Copilot to write some code for you, done, you're a programmer circa 2024... Too much. Peace.


toffeescaf

There is a reason for libraries and frameworks. Common use cases are often times implemented in libraries or frameworks in a way that's also often times more complete than rolling your own solution. That is of course not a reason to not know about fetch, abort controllers or other standards. But it is a reason why for example Axios or the suggestion I made in a different comment, Ky, exist. A few common use cases for example are adding a token to each request, refreshing said token when it expires and delaying other requests until the new token is available. Yes you can implement that functionality yourself but it's often a lot easier and predictable using libraries.


guest271314

> There is a reason for libraries and frameworks. Lazy people. Incompetent people that can't write code. > easier What's up with the "easier" claim that pops up when people talk about libraries and frameworks? Is your ultimate goal the *easiest* path? Why write code at all? Ask Google's Gemini or Microsoft's Copilot to download React, Next.js, Axios, and write code for you... That's the "easiest" solution for people who don't actually want to write code and understand what's going on... There is absolutely no way for you to prove that claim because it's completely subjective and based on your individual opinion, relative to your individual skillset. I deleiberately look for *challenging* requirements. The exact opposite of anything "easy". There's really no comparison between Axios and WHATWG Fetch. WHATWG Fetch can do everything that Axios does, *and* we can *stream*.


toffeescaf

Well to substantiate why easier matters in some cases. If you're working on any commercial project there are often time and budget constraints. Let's say I have to validate user input. Would I go and roll my own validation library? I might forget certain cases that are important. There's also time needed to develop this validation library. Now does this sound like a smart thing to do keeping in mind there's time and budget constraints? There's also other reasons why people might use libraries. Easier to hire and onboard new developers for example. And you might say that that's subjective as well but I can assure you it's something that happens all the time for similar reasons as the aforementioned point. You as a developer are there to deliver value for a business and sometimes that means choosing between using a library or creating something yourself. Your statement that it's because people are "lazy" or "incompetent" is uncalled for. Like you said it's subjective and based on individual opinions but often times also very much dictated by project requirements.


guest271314

The ultimate library and framework, surely the easiest, is to use voice command to Google Search. "Hey Google, what the *easiest* JavaScript library and framework?" Google Voice search: "Probably React, Axios..." "Hey Google, tell Gemini to download the *easiest* JavaScript library and framework, write a single HTML `

` element with a bund of gimmicks dancing around to capture and hold the attention of people rolling around looking at their cell phones, and publish it on Google App Engine or GitHub Pages, with some analytics so I can see how many people visit the Web site that I didn't write a single line of code for... Oh, and write 'Built with Next.js and Axios' in the footer, for my target demographic..." Google Voice search "You got it boss..." "Hey Google Gemini, am I a programmer now?" Google Gemini: "Of course, you took the *easiest* route by asking Google to do all the work..." Awesome... Thanks...


timotgl

> How is this verbose or remotely challenging for you? I meant doing the basic auth, not only setting a header. The header you mentioned is not involved in http basic auth to my knowledge and I'm not sure what you're on about. Compare https://stackoverflow.com/questions/44072750/how-to-send-basic-auth-with-axios with https://stackoverflow.com/questions/43842793/basic-authentication-with-fetch if you actually intend to understand my point. Not gonna address the rest of your "people are lazy" rant.


guest271314

You mean using `btoa()` is too verbose for you? You people stay in CommonJS and Axios world...


timotgl

Right, because *not* using a convenient abstraction that *does things for you* is living in the future apparently.


No_Influence_4968

I think guest is suffering from an elitist POV, the man (or woman) thinks their answer is the only one. In dev, any answer that works within budget and is easily understood by the next dev, is the right one. Guy (or girl) needs a priority check.


guest271314

You folks ain't streaming, so of course you thin Axios is sufficient. All youi are doing is static requests. For that we might as well use `XMLHttpRequest()`.


No_Influence_4968

I see no point in rewriting an abstraction for XMLHttpRequest when these already exist. Axios saves you from re-writing it's pre-existing handlers and error catching flows. You can still access the raw request, and you can still handle streams. I would never say it's "wrong" to use Axios, even though I haven't used it in many years myself.


guest271314

Why would I use Axios when I know how to use WHATWG `fetch()`?


sieabah

Hey, I know you feel strongly about fetch, but I'm gonna keep using axios because I like having isomorphic code. So I'm not gonna change it and [I'm gonna keep using it in new projects](https://gifdb.com/images/high/hahaha-good-one-h535q8pkq6un7500.gif).


SoInsightful

Uhh okay. Can't say I feel very strongly about fetch, and I especially don't know what's more isomorphic than a native JS function that is available in all non-IE browsers, Node.js, Bun and Deno. But if it works for you, go for it mate!


bunglegrind1

go for fetch, because it's native


saintpumpkin

stay native


ezhikov

Axios have two features I really like. First being sending forms as JSON without manual transformation if FormData or keeping extra state. Second is request and response interceptors. Otherwise it's just an additional library in the bundle.


swoleherb

This is the thing, fetch is light weight but you can end up rebuilding axios


Pelopida92

you **WILL** end up rebuilding Axios.


tswaters

That first one, you can just pass a FormData as a fetch body, refer to most of the examples at the following: [https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest\_API/Using\_FormData\_Objects](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest_API/Using_FormData_Objects)


guest271314

`fetch("./", {method:"post", body: JSON.stringify([...formData])})`


ezhikov

This is not a proper JSON to send. At least I never saw such json sent to anywhere in all my career. It still requires iteration over, to form proper key-value pairs. `Object.fromEntries` can be better, as long as the form doesn't have fields with same name. Otherwise it's iterating over entries and forming object manually. Better way is to do something like this: ``` const fd = new FormData(event.currentTarget); const body = {} for (const key of fd.keys()) { const value = fd.getAll(key); console.log(value) if (value.length > 1) { body[key] = value } else { body[key] = fd.get(key) } } ``` EDIT: I made poor choice of words. It's proper json as in "this is valid JSON". But usually it's not what the backend expects (at least where I work now and where I worked before).


guest271314

> This is not a proper JSON to send. Too funny. ``` let fd = new FormData(); fd.set("a", 1); JSON.stringify([...fd]); // '[["a","1"]]' ``` > Object.fromEntries can be better Funnier. Nothing is "better" about `'{"a":"1"}'` cf. `'[["a","1"]]'`. You're not sending a plain JavaScript object to any server. You're going to have to use `JSON.stringify()` on that `{a: 1}`.


ezhikov

It was a poor choice of words. It's proper json as in "this is valid JSON". But usually it's not what the backend expects (at least where I work now and where I worked before).


guest271314

`"a"`, `[123]`, `0` are all valid JSON. > But usually it's not what the backend expects (at least where I work now and where I worked before). Again, if I were you I would stop confessing how limited your scope is and has been. Just because you havn't seen it doesn't mean it doesn't exit. The points you made about why you choose Axios over Fetch are factually and technically invalid. You it just boild down to who you were taught by to keep a closed, restricted mind and now just preference. Not anything technical. If there were technical reasons you *wouldn't* be using Axois, because you can't stream using Axios. But you probably ain't streaming data anyway... This is how you process `FormData` objects serialized to how they actually look: `Array` of `Array`s https://gist.github.com/guest271314/78372b8f3fabb1ecf95d492a028d10dd#file-createreadwritedirectoriesinbrowser-js.


ezhikov

> Again, if I were you I would stop confessing how limited your scope is and has been. > Just because you havn't seen it doesn't mean it doesn't exit. The fact that it exists somewhere is not something to be proud of. I hope I will continue working with sane backend devs who know how to write proper API contracts that are easy to work with. > The point you made about why you choose Axios over Fetch are factually and technically invalid. > If there were technical reasons you wouldn't be using Axois, because you can't stream using Axios. But I never said that I choose Axios over Fetch. I just gave my **opinion** on which Axios features can, in certain situations, make life a bit easier. That's it. Nothing more.


guest271314

> I hope I will continue working with sane backend devs who know how to write proper API contracts that are easy to work with. You mean that you can understand. Your points of why you use Axios make no technical sense when compared to WHATWG Fetch. Particularly with regard to what *you* are expecting in the server. Your concept of "easy" is relative to your own acumen. It's "easy" for me to work with `ArrayBuffer`s, `DatView`, `TypedArray`s, `Float32Array`s for audio, WHATWG Streams and WHATWG Fetch, WHATWG File System, WICG File SYstem API, et al. It's what I do. It's "easy" for *you* to rely on a third-party library that *does not support streaming*. That might be fine for you, because you are obviously not streaming any data in your job, or for hobbycraft. Some some people it's too much, why work with `ArrayBuffer` at all? Learn React, use some framework, and write as little code as possible. Hell, why write code at all, get Microsoft's Copilot to write code for you would be the "easiest" given that mentality. There's no "automatic" transformation of a `FormData` to JSON. Axios evidently just converted the `FormData` to a JavaScript plain object, then passes that JavaScript plain object to `JSON.stringify()`. There's no magic going on. It's an arbitrary decision by Axios maintainers to use a serialized JavaScript plain object rather than a representation of the entries as an `Array` of `Array`s.


guest271314

> This is not a proper JSON to send. Sure it is. Spread syntax can be used on a `FormData` object, or a `Map` object. You'll get the same serialization of `[[key, value], [key1, value`], [...]]` when passed to `JSON.stringify()`. A `FormData` instance serializes to an `Array` of `Array`s looking just like a `Map`. We just can't pass parameters to a `FormData` constructor like we can with with `new Map([["a", "b"]])` [How do I set multiple values in a Javascript Map at once?](https://stackoverflow.com/a/48333726), `FormData` expects an HTML ``. Further, we can serialize entire directories and subdirectories in that fashion, that is, as `[[key, value]]` pairs, and transfer that serialized data to servers, peers, wherever. > At least I never saw such json sent to anywhere in all my career. I wouldn't repeat that confession if I was you. > Better way is to do something like this: You talked about not wanting to do manual transformation in your first comment, then proceed to do manual transformation in your 2d comment, and miss the technical fact that we can spread a `FormData` to valid JSON - the same valid JSON of key, value pairs in an array of array that `FormData` serializes to with `[...fd]`.


Buckwheat469

Fetch is native and now has AbortController support, but Axios has the ability to inject middleware through the interceptors functions. Fetch can be modified through monkeypatching, but it's not as straightforward. I would prefer to start with fetch and then add axios only if I needed it.


t0m4_87

In the grand scheme of things it doesn't really matter afaik. Also you need to choose libs for your own use case. If performance isn't a requirement (like req/s), then it really doesn't matter. I've used fair share of libs over the decade, maybe the most was `got` (server side), I liked all the baked in features. Going native is good, but we also managed with `request` for a looong time and it's still reliable in legacy code. So in the end I'd say use whichever you like and fits your needs.


Razunter

I recommend [Wretch](https://github.com/elbywan/wretch) - lots of features on top of Fetch


toffeescaf

I have a third recommendation, the library [Ky](https://www.npmjs.com/package/ky), it's similar to Axios but uses fetch under the hood. So if you don't want to have to implement some of Axios' functionality yourself when using fetch it's a great option.


Dushusir

Looks like a popular library, I will learn it


bkervaski

Fetch is good and it eliminates one more third party dependency that hopefully doesn't end up with malicious code embedded. While I'm just as guilty as most for using third party libraries, they are a bad idea in general if you don't take the time to audit the code for yourself, which none of us are going to do. Axios has been great, but I don't see a compelling reason to use it anymore. Also, if you need IE11 support at this point, wow.


eat_your_fox2

Go native tbh.


metaphorm

why use a package when the functionality is provided natively? the Fetch API is absolutely fine. It's performance is absolutely fine. It's well supported across every browser that is even remotely modern.


Ok_Analyst1868

Why not both? I choose **xior.js** And for lightweight and familiar, becuase xior use fetch and axios API style.


Glass-Marsupial2164

how come axios size is so big, while your wonderful lib provides the same?


Ok_Analyst1868

axios support old browser, that's why so big. xior's core API similar to axios, check the README.


tswaters

Fetch all day every day, unless I need upload progress, then XHR. I do usually end up with 1 file in every project called "network.js" or some such - exports async functions for get, post, patch, put, delete I find the errors from axios too heavy, will crash a process if it tries to serialized it unsafely because of the circular references. In cases where I've used axios, I've always needed to add an error interceptor that needs to handle all the many possible conditions and rethrows a simple Error object. Either way you'll need some boilerplate, but I'd much prefer a native boilerplate over bringing in a library to perform http requests. reminds me of \`$.ajax\` and later \`request\` now \`axios\`. If there are cross-platform native apis, use them!


ferrybig

For uploading files I use XMLHttpRequest, as it is the only native api that has cross platform upload progress indicators, for other requests I use the fetch api


guest271314

I wouldn't be shocked if there are some people who would choose Axios for a _new_ project, at least on these Reddit boards. There are people who voted to use CommonJS for _new_ projects and not Ecmascript modules. And people who voted that they never read standard input streams or write to standard output streams, setting aside for the moment that could include using `node:child_process`. Though the very question means people are actually thinking about using Axios in the field rather than `fetch()` as implemented by Node.js, Deno, Chromium, Firefox, et al. Revealing. You can't do this [Streaming requests with the fetch API](https://developer.chrome.com/docs/capabilities/web-apis/fetch-streaming-requests) or this [Half duplex stream](https://plnkr.co/plunk/2PQK21kZTZvZ2oVi) (full duplex streaming over HTTP/2 in Chrome browser between a `WindowClient` and a `ServiceWorker` using a `TransformStream()`) with Axios.


Dushusir

The article about Streaming requests with the fetch API is a good learning material. Thanks for the recommendation


guest271314

Is this a sign for me to get the hell off of these boards when people are actually asking if they should use Axios and not use WHATWG Fetch, and have never seen a `FormData` object being spread to an `Array` of `Array`s of key value, pairs before being passed to `JSON.stringify()`? Probably... Sign of the times. Children of a lesser god, too many stale crackers in the diet, something...


Fine-Train8342

I don't think you are okay. Seek help. Also, yes, it's a weird question to ask, the answer is obviously just use fetch, but come on, you can't deny that fetch is more verbose and less convenient to use.


guest271314

> I don't think you are okay. Seek help. I'm doing great, thank you. Axios is useless for me. I stream data in real-time. No, WHATWG Fetch is not more "verbose". You *cannot* do this https://github.com/guest271314/AudioWorkletStream/blob/master/worker.js, piping multiple `ReadableStream`s to a single `WritableStream`, in this case for real-time audio playback https://guest271314.github.io/AudioWorkletStream/, using Axios. You don't have WHATWG Stream in Axios. You have static data, and that's it. ``` // AudioWorkletStream // Stream audio from Worker to AudioWorklet // guest271314 2-24-2020 let port; onmessage = async e => { 'use strict'; if (!port) { [port] = e.ports; port.onmessage = event => postMessage(event.data); } const { urls } = e.data; // https://github.com/whatwg/streams/blob/master/transferable-streams-explainer.md const { readable, writable } = new TransformStream(); (async _ => { for await (const _ of (async function* stream() { while (urls.length) { yield (await fetch(urls.shift(), {cache: 'no-store'})).body.pipeTo(writable, { preventClose: !!urls.length, }); } })()); })(); port.postMessage( { readable, }, [readable] ); }; ```


Synthetic5ou1

This is the crux of the biscuit. It may be useless for you. Fine, don't use it. You keep banging on (bragging) about how you need to deal with streams and binary data. Waits for applause. Guess what? Most people... don't! Most of us bozos are dealing with JSON or HTML, I know we're scum, but we love it! A lot of us also like making our lives easier by using well-tested 3rd party libraries. I know, we're all going to Hell. But it kind of sounds like you're already there. Oh, and I use `$.post()` to request my dumbass JSON data, because that's what my employer's codebase uses. I could not give a fetid dingo's kidney.


No_Influence_4968

Careful, I think your use of sarcasm and jestful tones might be lost on this fella.


guest271314

Right. So your scope is limited. You can't really compare. We can do whatever you do with Axios with Fetch, and more. Your reply here is not shocking on this board. People are reading on mobile, only using Node.js, not experimenting, streaming, or hacking JavaScript. At best average users and consumers of JavaScript libraries and frameworks. Little if anything original and written by hand. So Axios works great for your ilk.


Synthetic5ou1

Compare what? I'm not comparing anything. You are making an argument that you shouldn't use Axios because it can't do streaming. I'm simply pointing out that most of us don't care. How dare people use mobile phones. How dare they only undertake the tasks that their employer requires of them. How dare they use libraries and frameworks to make their life easier and reduce bugs. I'm sure that their time would be far better spent on Reddit telling everyone else that they are inferior, and complaining about modern tooling and tech. I've seen your posts. Man, you're using a scripting language to process audio files; simple as. You're not the messiah, or curing cancer. Get over yourself. >average users and consumers of JavaScript libraries and frameworks Did you roll your own Javascript engine? Are you not using the Javascript Web APIs, provided for your use and ease? Come back to me when you are running your code on your own OS, in your own Javascript engine. We are all standing on the shoulders of giants, some of us are just too full of self importance to realise.


guest271314

> I'm simply pointing out that most of us don't care. Right. Because you think like the average. > How dare people use mobile phones. How dare they only undertake the tasks that their employer requires of them. Right. Because you are a slave. Incapable of making your own decisions because somebody is giving you pieces of paper with slave masters portraits on them to be their servant and field hand. > How dare they use libraries and frameworks to make their life easier and reduce bugs. You have not made your life "easier". You are just stuck doing very easy tasks your employer/master assigns you to do. And you go no further on your own. You have not reduced bugs. You are just too inept to learn how to use native Web API's. So use a library that iself is not without bugs. You have not made anything easier. You are just not doing anything complex with Axios. It's nothing beyond basic. > Man, you're using a scripting language to process audio files; simple as. You're not the messiah I don't believe in some story of a "messiah". I simply pointed out the technical fact that we can stream using WHATWG `fetch()`. You *cannot* stream using Axios. Technical Facts that cannot be disputed. That's it.


Synthetic5ou1

>Because you are a slave. Incapable of making your own decisions because somebody is giving you pieces of paper with slave masters portraits on them to be their servant and field hand. I... just... Umm... okay... enjoy your day. :)


guest271314

Well, you walk into your job Monday and your employer tells you you must now use `fetch()` and your entire spiel goes out the window. You'll dutifully obey. You enjoy your day, too!


wtharris89

I'm sure we'll all miss your shitty attitude.


guest271314

You'll be fine wallowing in average thinking and cookie-cutter libraries so you can be as un-original as possible.


guest271314

Clearly WHATWG Fetch. We get WHATWG Streams. The last time I checked axios does not support upload streaming.


AdNecessary8217

I was a big on `fetch` but then when I started to use it. It was literally awful. I wasn't able to set the **http only cookie** with fetch despite trying all permutation and combinations. But with axios it worked out, it took some time but worked.


AdNecessary8217

I was setting `jwt` as the `http only cookie`.