Sending JavaScript Http Requests with the fetch() API

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
this is the second video in a short mini series of free videos where I have a look at common ways were of typical ways of sending HTTP requests in a front-end JavaScript application to a back-end in the previous video which you should absolutely check out link below the video of course we had a look at XML HTTP requests in this video we'll have a look at the fetch API it is better than XML HTTP requests in some aspects but in some aspects it's all the worse and I'm just talking about the basic functionality so let's have a look at how it generally works and see how you can use the fetch API in your projects so now I want to rebuild with the fetch API what I already built with xmlhttprequest in the previous video now definitely check out that video if you haven't already of course therefore in there we used xml httprequest in a utility function and we promised a fide it by wrapping it with a promise so that we can send a get in a post request append data and also handle errors we also made sure we attach to write header now we'll rebuild the same thing with the fetch API so for that let's start with the get request the fetch API is a relatively modern addition to the browser and not all browsers support it especially older browsers Internet Explorer of course does not support it so if you need support for dad and you don't want to add a polyfill or anything like that you should use XML HTTP request here however I'm working in chrome so I'll use the fetch API and we can use it by calling fetch this is a globally available function made available by the browser in JavaScript and you can use it to send a HTTP request now we're using the request dummy API here and in there you get a couple of dummy endpoints to which you can send requests they're not returning real data and you can't create real data there but you can fake all these operations and here I want to get a list of users for that we can send a get request to this URL which is exactly the same thing we did with the XML HTTP request so it's this URL I want to send the request to and therefore here on the fetch function we just have to pass in that URL now without any additional configuration this will send a get request to that URL which is exactly what I want now fetch unlike XML HTTP request by default uses promises so without any extra work without wrapping it with a promise manually we can add a then method here and utilize our response now if we console lock the response here let's see what we get if we save that and we then make sure in index.html that we import fetch jeaious here instead of xhr jeaious we can go back to our little application here simply opened with a double click we need no def server for that if we now reload that and click get data we get our response object now in that object we get a couple of interesting features get the status code whether the response was treated as ok so if it was successful has a 200 ish status code essentially we got the URL we got some headers that were part of the response and we got the body and now the body is a readable stream that's not too great because we can't really work with a readable stream here I want the snapshot I want to snap shut off the returned data I want data which this request should actually return which should look like this now for dead the fetch API has a utility method we can call on the response object and that's response dot jason if the response body should be json data which it should be for this dummy api then this will convert the stream body to streamed body into a snapshot and automatically parse JSON data to native javascript datatypes if you have a different data format let's say text you also have a text method which transforms the stream to a snapshot and does not do the JSON parsing for example and you get a couple of other methods as well so we need to call this to convert our streamed body into a snapshot and to also then as a extra convenience convert to json data to javascript datatypes now the jason method itself returns a promise so we can return the result of this and add another then method to this promise chain in promises or when working with promises we can chain multiple then methods to execute multiple steps and this return promise here is basically merged with this main promise chain and in the next ven block we therefore have access to the result this promise the promise created by the jason method resolves - which will be our response data here so the response data is now the interesting part let's login and see if this is now the data we expect if we save that and we now reload and click on get data this looks much better so this is actually all we need for getting the data you could of course now render this on the screen that's not really what I want to show here instead this is how we can use the fetch API here and how we can get data transform it and use it now let's all make sure we can send data now for dead we can of course duplicate this code here and just make sure we send a post request there now just as with the XML HTTP request I'm not the biggest fan of code duplication though at least with the fetch API we have less overhead we don't have all these extra steps we had with xml httprequest so i think it would be fine to indeed execute it again like this without any wrapping utility function nonetheless I want to create one I'll name it send HTTP requests here as well and this should be a function that takes a method and a URL and data that should be attached and in there I want to send the fetch request return the result of that and now of course exchange this URL for the URL argument here and then also make sure we later utilize the method ends on now first of all here with get data I therefore want to call send HTTP request here when I send a get request here of course and then to this URL and now regarding the handing of the response I think this extraction of the response body that's something that fits quite well into this utility function but of course what we do with the response data should not go in there so I'll remove that last step in the utility function and here when we call send HTTP request we therefore can get rid of that response data extraction step and we get the response data right away because we do the extraction in the utility function so we have that now we have our response data which we log now and let's verify that this still works by reloading and clicking on get data looks good and now we can utilize send HTTP request also here when we try to send data here i want to send a post request and the URL actually should be this register URL here so API slash register and they offer here I'll copy that URL but I'll change users here for register now here we also want to append some data and that can be a JavaScript object here now to get a success response as we learned in the last video we have to send exactly this data here so I'll copy that copy that into my object however converted to normal JavaScript object we don't need the quotes around the object keys here and once that we should be good almost I also want to handle any response data we're getting back so that we can see whether we succeeded or not like this and with that we just need to tweak send HTTP request to make sure that in there we do utilize the method and the data because right now that is not happening right now we're always just sending a get request now to tweak that request we can pass a second argument to fetch this is an object that allows us to configure the outgoing request if you hit control space here in visual city code you see there are a bunch of things you can configure a lot of niche options which you don't need it often but for example you can set the method and that by default is set to get and therefore you don't need to set it if you always want to send a get request but here I wanna set it to method so to the argument value I'm getting here so that we are able to dynamically set us and to either send a get or maybe also a post request now we also can add body here to attach a body to the outgoing request now the body here should be JSON data and therefore all json stringify the data package we're getting this might be undefined like in this scenario here but then we just don't add any body and we don't need any body for a get request and the effort this shouldn't be a issue so now we have the body which is added here and with that we're almost there in the last video we also learned that we need to attach a header the content type header to make sure the API doesn't fail and hence we should do this here as well for that we can add a headers object and now I want to see I want to check if data is set with a ternary expression if it is true C then header should be an object that includes a content type key where the value is application slash Jason otherwise I want to add an empty object and this basically is how you add headers with the fetch API you can have as many key value pairs here as you want in this object and they will be appended as headers to the outgoing request here I'm using the content type header with this default value otherwise if data is faulty I'm setting this to an empty object which means I don't add any special headers so now this should be more flexible and if we now check this with that data we found on the official docks after saving everything if we reload this page and we click on post data that's looking quite good that is a success response now let's also simulate an error and to do that we can comment out the password so that we don't send the password data if we do that and we save it and reload if we now click post data we get an error here the problem is we still get the log from line 25 which means we still make it into this success then block so maybe try adding catch here write add catch catch any potential error and then maybe lock this error here of course you could implement more sophisticated error handling here now if we do that let's see if we now get some output from line 29 let's reload and click post data and we don't we get it from line 26 which still is our success case this is exactly the same problem in quotes because it's actually the intended behavior we saw in the last video with xml httprequest errors which are not technically errors which means errors which are not related to network issues or anything like that but errors where we get a successful response where we just have a non success status code 400 or 500 are treated as successful responses by the fetch API and the same was the case for xml httprequest so we make it into the success handlers so to say even if we have a error status code because technically it's a valid response the requests left our application without issues and we got a response without issues which is why no error is thrown by default now of course we nonetheless have a error case here we're not happy with the result we have an error which we want to handle now for that we can do something similar as before in the success handler we want to check the status code now thankfully here in our send HTTP request function the response object has a status property which we can check and this gives us the status code and if that is greater or equal than 400 then we're not happy with the response an alternative would have been to check the response dot okay field which is true for successful responses so for 200 ish codes and false otherwise but this will work as well so if this is greater or equal than 400 we know excuse me here we should have checked for naught okay so here if we are have a code greater than 400 or equal to 400 then we have an error an error status code so here we want to basically throw it error and if we throw an error here in a venn block this will effectively reject the outer promise so that in the promise chain where we listen to the outer promise we would make it into a catch block so here we can throw a new error and maybe you say something went wrong but maybe we also want to add some extra content to the error so actually I want to create an error object here with new error something went wrong where I add extra data which should be my response body and now that's where we have a problem with the fetch API the response body is not available in this step learned we have to parse it and error responses are no difference because technically they're exactly the same kind of responses as success responses so the body at this point here in this Venn block here is that streamed body not the snapshot so if I want to attach the response body here that's just not possible now that's of course pretty annoying what can we do to mitigate that well we can cut that code for now and in that if case here we could actually call response JSON which gives us a promise and now add a Venn block here therefore we have a nested promise chain in this outer promise chain which is never that great but here actually it's a good solution where we now will have our error response data so to say and now in here we can create our error assign the error response data to the data property of the error and then fro error and now we just need to return this inner promise chain here so that it becomes part of that outer promise chain because if we return something in that promise chain we merge it into the promise chain so to say there's something we return here itself is in the end a promise which is rejected because we throw an error inside of it so that's what we do here in the error status code case since we returned we need no else statement and otherwise we just return Jason like that so now we either return a promise that will throw an error or we return the body data this is how we can handle it but we need this extra inner this wrapped promise chain here because of the way the body has to be parsed with the fetch API with that however we should make it into this catch block here if we do have an error and therefore if we reload and click post data now we get output from line 37 something went wrong which is my custom message so that looks good in line 37 now indeed is the catch block and here we could also access error dot data and retrieve that data I'm storing here in my custom error-handling logic so if I now reload and click post data we see that error data is all the part of the output so this is how we can use the fetch API generally it's nicer than xml httprequest has a nicer syntax I'd say but easier to use less clunky but browser support is worse which means you might need a polyfill and in addition this error handling logic can be annoying it's not that different from the error handling logic we have in xml httprequest but at least there we didn't have that extra response body parsing step we do have that here in the fetch API which means we have to find a solution like this inner wrapped promise chain nonetheless of course is up to you which one you prefer fetch at least uses promises natively which is a plus and might have some other syntax features which you like and therefore it is a bit more popular but definitely XML HTTP request is still also getting used a lot actually it's always getting used by the access package which is the package we'll have a look at in the last video of this mini series now with this video you hopefully have a basic understanding of how the fetch API works how it compares to XML HTTP requests and how you use it now let me also note that we just had a basic look at it of course there are more differences in in the detail when it comes to sending cookies to a backhand and stuff like that but generally you hopefully already have a good understanding of how it compares where it's better and where it's a bit more annoying to work with it now turns out we have another great option for working with HTTP requests and that's the Axios library that's what we'll have a look at in the last video of this miniseries
Info
Channel: Academind
Views: 46,896
Rating: undefined out of 5
Keywords: fetch, javascript fetch, js fetch, fetch api, javascript fetch api, js fetch api, axios, xmlhttprequest, fetch vs axios, fetch vs xmlhttprequest, tutorial
Id: 23hrM4saaMk
Channel Id: undefined
Length: 18min 11sec (1091 seconds)
Published: Thu Sep 19 2019
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.