Это видео недоступно.
Сожалеем об этом.
JavaScript Fetch API - One Mistake I ALWAYS MAKE!
HTML-код
- Опубликовано: 4 окт 2023
- Don't make this mistake using JavaScript fetch!
The fetch API only throws an error if you the response is a 500 status. Otherwise, it doesn't throw an error. This means it's your responsibility to ensure the response has come back successfully with a status of 200. It's your responsibility to handle any other type of status like a 404.
*DISCORD*
Join the Learn Build Teach Discord Server 💬 - / discord
*STAY IN TOUCH 👋*
Newsletter 🗞 - www.jamesqquick.com/newsletter
Follow me on Twitter 🐦 - / jamesqquick
Check out the Podcast - compressed.fm/
Courses - jamesqquick.com/courses
*QUESTIONS ABOUT MY SETUP*
Check out my Uses page for my VS Code setup, what recording equipment I use, etc. www.jamesqquick.com/uses
Minor correction: Fetch only throws on network error (can't connect, connection interrupted, DNS failed, etc.) but not on status code 500. Every valid http request-response cycle is just that: valid for fetch. The interpretation of the status code is left to the developer.
Ahhh great point! Thanks for clarifying that!!
This isn't a minor correction.
I work for a banking firm and we have built so many custom tools and wrappers around literally everything that sometimes I forget how these APIs work in their base form.
Appreciate you James.
You're very welcome!
i like to throw error with status code if(!response.ok) and then in the next if statement check if the response is json, because sometimes you receive templates and you want to handle that as well, if everything else goes right i return the json
That's a great option! Thanks for sharing that!
Yeah, I think this is the "correct" way to do it. Though less common, there are other HTTP statuses that may accompany a still-successful request.
I try to route all my requests through a single service and run my response through a handle error function that returns an alert with the error status code and status text.
@@JamesLaenNeal yep, best approach is to discuss with the backend about specifics, usually each team requires different ways to handle the status codes, it's not jack of all trades, also libraries require specifically to throw errors so they can catch it in the view and manipulate the view according to the error, (example show a popup if a post request failed), TanstackQuery one of the libraries
The `Response` interface has a property that allows you to check whether or not the response was successful (200-299). So you can just write: `if (!response.ok) { ... }`
This is what I always do
oh thanks
I did that mistake quite a few times. There is res.ok property that can be checked. If not true I usually throw an error
Ah that's a nice one as well!
Excellent! I'm a professional RUclips uploader myself and I'm quite aware how difficult it is to make a single video. Bravo! Keep up the good work.
Thanks for sharing James. I thought the catch() method catches all types of errors.
I always assume the same thing lol Fetch doesn't consider other statuses except 5xx to be errors
if I check
if (!response.ok) {}
is it not the same?
That makes sense, we should be checking the status code!
Quick Question: How can I show fcm notification in foreground instead of toast or new Notification() without action button support.
In this video, the console.log output is displayed right next to the source code.
Is this a vscode extension? It looks very useful!
it's quokka
Yeah its the quokka extension. It's so good!!
Thx bro!
Very helpfull video James! I also thought, that 4xx is error which should be catch :-D. Can I ask you, I assume you are using quokka and you have to use 'node-fetch' library for create API requests, this library is installed globally or somewhere in your project? Thanks! :-)
Yep, using Quokka. With Quokka it gives me the ability to install packages for a given file. I think that's with the paid tier though. It may not be available on free tier. Try it out and let me know!
I'll keep using axios 😂 still gets the job done very well.
haha whatever works
Us too using an interceptor to handle error status codes, makes for a lot cleaner code
I think the proper approach is, when you develop a JSON REST API, you must send the body always in JSON format, including when the status is 4xx or 5xx. So the basic error is in the API implementation, but of course, you have to deal with this in the case of some APIs.
Hi James, noob question but how do you get directly your console.log in the IDE next to it? : O thanks
It's the Quokka extension. really cool. Highly recommend it :)
@@JamesQQuick thank you!
You're very welcome! That's what i'm here for!@@Okir09
Probably should also check if the content type is application/JSON.. we once had an nginx proxied rest API throw from nginx because the upload payload was too large and it returned an html error page which the UI code gladly tried to parse as JSON 😅
Ah yes another great callout!
Great video!
I'm not sure to get the point, if in both case(40x and 50x) we get an error in either the fetch or the json. In either case, I would log an error with all the info I could have(url and status) and provide some error status after.
What if the server responds with a status 400 and returns valid json telling you what you did wrong in the request? Fetch wont throw and neither will json parse. Point is you have to look at every api specifically.
Yeah the overall point is you have to inspect the response appropriately to ensure it's doing what you expect
good to know
Great video
Could you make a status switch statement
Absolutely you could!
why do you have import here? Is it because it is a REACT.js fetch?
which extension is that that shows json response within vscode?
It's the Quokka extension! It's awesome :)
@@JamesQQuick Thanks!! It seems really useful! I'm installing that right now. Good job and thanks for all your videos. Very informative and interesting.
Yeahhh! Let me know what you think :)@@braveitor
How you calling the await method without the async function
Latest versions of node allow you to run top level await :)
@@JamesQQuickdidn't know that wow!! so many new information, james thanks a lot!
Yeah! Happy to help :)@@cranberry888
hey its helps me
whats that quokka thing in the terminal?
It's an extension that live reloads your code. It's really awesome!
@@JamesQQuick oh will try it
Nice one
Should the catch block catch all errors in fetch? Why hasn't that been the case yet if fetch has been here for so long already
Catch block while catch all errors, yes. The point is that Fetch doesn't consider most things to actually be an error.
@@JamesQQuick ooh, so it's the fetch that's the problem here, have they not fixed it yet or is fetch fundamentally different?
Because I heard in many videos that fetch will always return a response in it's promise, it won't throw direct error, is this what they were referring to?
That's mostly true. As @ghandmann1 said below, "Fetch only throws on network error (can't connect, connection interrupted, DNS failed, etc.) but not on status code 500. Every valid http request-response cycle is just that: valid for fetch" @@blackpurple9163
@@JamesQQuick so your implementation will catch most of the errors right?
I'm new and was taught to use axios, but fetch is how I learnt promises and async-await so fetch is what I prefer, and less libraries I ship the better I think my end product will be
Using try/catch means all errors will get caught from any code that runs inside of the try block. You just have to manually inspect the response from the fetch request to make sure it returned the status you expect.@@blackpurple9163
Great!
This kind of annoyed me coming from axios. But then I realized that’s fetch’s api is actually much nicer.
It assumes that if it gets a server response, its job was successful.
Who’s to say you aren’t calling some wacky API where 500 is an acceptable and expected status code
And I don’t want libraries choosing to throw exceptions for non exceptional things
If I give it an endpoint that it is unable to connect to, then I am fine with the exception being thrown for me
Yeah axios is great also. Just depends on what you need to do with the response.
thx.
You're very welcome! Have you made that mistake before?
Not checking the status of an API request is pure amateur or hubris of the part of the programmer. Catching the error as early as possible saves countless hours of debugging.
Nice
wtf,who deserialize a request without check status code xd
for me, i'll just make my api return json {error: "Not found"} with status 404 then it's fine to do await res.json() from js 😂
haha yeah that works if the API is built that way. Depends on the API
Mistake...? 🤔💭
,,Into the flood again
Same old trip it was back then
*So I made a big mistaaaaaake*
Try to see it once my way!" 🎶
(Alice in Chains)
🎉
A tiny correction: developerasaurus isn't a valid pokemon... yet. Give it time, Nintendo have already started scraping the bottom of the barrel that's why I try to ignore anything post Hoenn 😂 (gba).
haha one day I'd love to see developerasaurus become a real pokemon :)
The JavaScript Fetch API is a modern and powerful built-in feature that allows you to make network requests (e.g., HTTP requests) from a web page or application. It provides a more flexible and promise-based alternative to the older XMLHttpRequest (XHR) API for making asynchronous requests to servers and fetching data from external resources like APIs, databases, or other websites.
Here are some key features and concepts related to the JavaScript Fetch API:
1. **Promises:** The Fetch API is based on Promises, which provide a way to handle asynchronous operations more elegantly and avoid callback hell. Promises allow you to write cleaner and more maintainable code for handling responses.
2. **HTTP Methods:** Fetch supports various HTTP methods, including GET, POST, PUT, DELETE, and more. These methods determine the type of request you want to make to a server.
3. **Headers:** You can specify custom headers in your Fetch requests, which is important when working with APIs that require authentication or expect specific headers.
4. **Request and Response Objects:** The Fetch API uses Request and Response objects to represent the request being sent and the response received. You can customize request parameters and handle response data using these objects.
5. **JSON Parsing:** Fetch makes it easy to work with JSON data, which is commonly used in modern web applications. You can use the `.json()` method on a response object to parse JSON data from the response.
6. **Error Handling:** Fetch allows you to handle network errors and HTTP errors (e.g., 404 or 500) gracefully, providing better error handling capabilities compared to traditional XHR.
Here's a basic example of how to use the Fetch API to make a GET request:
```javascript
fetch('api.example.com/data')
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.json(); // Parse JSON data from the response
})
.then(data => {
console.log(data); // Process the fetched data
})
.catch(error => {
console.error('Fetch error:', error);
});
```
In this example, we fetch data from the `api.example.com/data` URL, check if the response is successful (status code 200), parse the JSON data, and handle any errors that may occur during the request.
The Fetch API simplifies many common tasks associated with making network requests in JavaScript, making it a preferred choice for modern web development.
If you're interested in scholarships, you can explore opportunities like the one available at www.gildware.com/scholarship to support your education and career in web development, which may include working with the Fetch API for data retrieval.
wtf is this chatgpt type of response lol
bahahah feels like it!
Can't trust APIs to give you the right status code, what if guy who designed API decided to return you null or undefined, then there is no error. Best to read API doc so you know what to expect. This is a stupid JS design, it's not an error first language, instead we got to work with stupid try catch.
I made this error yesterday, stole about 30 minutes of my life 😿
hahah glad to know I'm not the only one
don't you get around all this by using the old `promise.then()` api? I still don't get why ppl are so crazy about the async-await syntax... it doesn't seem to do anything better than `promise.then()`
async-await is cleaner - while both accomplish the same outcome it is easier to read and reason about than a promise potentially followed by a chain of then clauses. However, knowing how and when to use both methods is preferable. You never know when you might have to read someone's source code.
@@0x007A that's the thing...I keep hearing everyone repeating that it's "cleaner", but to me it doesn't really look that way. I much rather see `promise.then().catch()` than async-await wrapped in try-catch clauses. the latter doesn't look cleaner in any way to me.
Cleaner is relative. I certainly think it's cleaner, but that's just my opinion. Regardless, you'd have the same issue if you used then/catch. You'd still have to check the response status before trying to parse JSON safely
@@JamesQQuick definitely subjective, that’s why I’ve kept saying “to me”. Those chained promise methods to me look much cleaner than the equivalent code wrapped in try-catch, if-else clauses… Looks more declarative.
Fair enough! Whatever works for you. To your original quesiton though, you don't get around having to check statuses when you're using then/catch. Similar logic has to be applied@@mario_luis_dev