9 ms·
Ajax Battle: XMLHttpRequest vs. the Fetch API
- tantalor 4y ago> XMLHttpRequest always sends browser cookies No: The XMLHttpRequest.withCredentials property is a boolean value that indicates whether or not cross-site Access-Control requests should be made using credentials such as cookies, authorization headers or TLS client certificates. https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/withCredentials https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequ...
- simlevesque 4y agoEven more important: it's value is `false` by default.
- re 4y agoThe blog post seems to only be referring to same-site requests for XHR, whereas your response is only referring to cross-site requests. A more complete correction would be: XMLHttpRequest always sends browser cookies for same-origin requests. They are not included for cross-origin requests unless explicitly requested. Fetch does not send cookies by default for either type of request, unless explicitly requested. Also note that the server must use the Access-Control-Allow-Credentials header for the response to be made available to the client code when making a cross-origin request with credentials. https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Credentials https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Ac...
- zwieback 4y agoThis is just one Ajax battle, many others were fought in the Trojan wars. I think we need some kind of JS-http thing called "Hector" which would be about as good as Ajax.
- dylan604 4y agoI always think it's about the football club
- pcan77 4y agoI always think it's the cleaning solution LOL
- JackFr 4y agoI mean there were even two Ajax's at Troy, Telamonian Ajax and Locrian Ajax.
- zwieback 4y agoOh right, totally forgot about that. Telamonian Ajax (aka "Greater Ajax") is the one I'm thinking of.
- dpcan 4y agoWho decides what is “cleaner” and “simpler”? It’s such a strange take in the coding world. I don’t know why other developers get to decide what is clean, simple, easier to understand, etc, when it comes to my code or the way I write code. I’ve been using xmlhttprequest for YEARS and honestly, it’s pretty dang simple. It’s pretty darn clean. And when we see it, we know what it’s doing and how it works. I’m not sure of the motivation behind changes and new API’s like this that keep trying to fix what really isn’t broken for most uses.
- melolife 4y agoIgnoring the fact that XMLHttpRequest is a hideously unlovely API, it's a huge problem when your primary asynchronous abstraction is not implemented by your primary API for async IO.
- iostream24 4y agoThat’s an opinion, not a fact, re: hideous etc. Please explain the latter bit again. I too see no need to switch suddenly to this fetch api when older browser support is important to my daily driver web app. I found the tone of this article condescending when browser apis have mega committee-ware battlescars all over them and likely implement both of xyz with the same call to epoll anyway, (joke about systems programming)
- ARandomerDude 4y agoif (xhr.readyState !== 4) return; is gross and stateful. Certainly you can learn it and use it but .then((res) => res.json()) is much more declarative.
- mmis1000 4y agoAnd if you forgot to call xhr.send() at the end. You screw up and your callback is never called. fetch doesn't even allow you to make this kind of mistakes.
- 4y ago
- RobertRoberts 4y agoThe only issue I have with Fetch is I can't get progress for up/downloading from it yet. Otherwise I prefer it over Ajax in every other way.
- ynniv 4y agoThis. Until fetch has all the features of xhr, what's the point of being pretty?
- tgv 4y agoThere are also fetch-like wrappers for xhr. Axios is a decent one, I think.
- mmis1000 4y agoI think fetch will never has all the features of `xhr`. At lease the sync `xhr` is not possible. The `promise` api don't even allow callback in `then()` to be called synchronized, let alone things like `fetch` that relies on it.
- TedDoesntTalk 4y agoIt’s also very difficult to save the received data to the browser as a file. It can be done with ugly hacks, but this should be supported natively in 2022. Background downloads are still a major PITA. Why?
- jjice 4y agoI don't have a lot of front end experience, but the way I've done it in the past was with <a download href="example.com/my/download/route"></a> and that always worked well for me. No idea if that would be helpful at all, I'm operating at a very surface level knowledge here.
- thunderbong 4y agoThat's the way to do if I want to just download a file. But the comments seem to be mentioning a scenario where they would like to download the file via Javascript.
- cyco130 4y agoI haven't seen XMLHttpRequest used directly in non-legacy code in quite some time. If there is any battle, it's between fetch and axios[1], and fetch is winning by virtue of being standard. Node.js also decided to implement it.[2] [1] https://github.com/axios/axios https://github.com/axios/axios [2] https://blog.logrocket.com/fetch-api-node-js/ https://blog.logrocket.com/fetch-api-node-js/
- redox99 4y agoWhat do you mean by winning? As in usage? Axios has many nice features (such as interceptors) and I think is just better than fetch, other than the fact that you need to add a few KB to your bundle of course.
- cyco130 4y agoYes, I meant usage. I agree axios has many nice features but fetch comes with 90% of what you need for free. Also, its API is spreading on the "other side" too. Service workers, worker runtimes (Cloudflare etc.) and Deno all use the fetch API for handling requests (as opposed to sending them).
- Jasper_ 4y agoI still write XMLHttpRequest and see no reason to switch. I depend on things like progress notifications and cancelations which fetch has iffy support for. https://github.com/magcius/noclip.website/blob/master/src/DataFetcher.ts#L96 https://github.com/magcius/noclip.website/blob/master/src/Da...
- ok123456 4y agoXMLHttpRequest has a synchronous version, where as fetch does not. For instance, this means you can do an XMLHttpRequest in your app's router, and decouple your presentation from dealing with endpoints. Fetch can't do this.
- zelphirkalt 4y agoYou could just await the async thing though, to make it synchronous.
- TedDoesntTalk 4y agoYou can use a async/await with fetch to force it to be synchronous.
- kevingadd 4y agoasync/await is not synchronous, it's promises under the hood
- TedDoesntTalk 4y agoBut from a programming standpoint, you are assured that the next induction Edie’s not execute until the response is received.
- kevingadd 4y agoFunctionally this is still very different from sync xhr. Changing from sync xhr to await+fetch will introduce new bugs into your application unless it was written carefully, because now code can run and interactions can happen during the fetch that would have been blocked by the sync xhr occupying the event loop. Promises are also specced so that their handlers don't run until the event loop completes a turn, which means that no matter what there is now an opportunity for queued callbacks to run before you actually process the response to your request, even if it hit in-memory cache.
- 4y ago
- imbnwa 4y agoYou can always wrap XHR with the success/error semantics you prefer with a Promise, or even, if you want to optimize, your own thenable interface.
- jokoon 4y agoUsing flask and about 2 js functions, I'm able to make an ajax webapp in about 100 lines. It's really amazing. Only problem is files. I'm serving video files locally, and for some reason the server stops returning file requests at some point. I was told to use a real webserver, but it doesn't seem trivial, at least on windows.