Sending JavaScript Http Requests with Axios

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
this is a video which belongs to a short mini series of free videos where I have a look at common options when it comes to sending HTTP requests from your front-end JavaScript application to a back-end in the first two parts we had a look at XML HTTP request and the fetch API definitely check out these videos if you haven't already you find links below the video in this video I'll introduce you to Axios a third-party library which actually wraps the XML HTTP request but which makes working with it much much easier and which in general makes sending HTTP requests really a breeze as you will see in this video so now after the fetch API and xml httprequest let's have a look at Axios now access is a third-party library a JavaScript library which we can use in any JavaScript project and it uses promises and nonetheless builds up on XML HTTP requests so it basically does what we manually did here in the first video where we wrapped XML HTTP requests and promised a fight it but of course the access library does is in a more sophisticated way offering us way more features and benefits it also has great browser support as you see because it uses XML HTTP requests under the hood and it's really easy to use now well not npm install it here because it don't have an NPM project we have a very simple project here we can just include it from a CDN by copying that link here and then we want to include it here above our own script that strip should also be fetched to access j/s now so that we use this script where we can write our exes logic so where's this import added and this import changed we're ready to write some code that uses the exes package now in case you missed the last two videos definitely check them out because there you'll learn the important fundamentals of all of that in this video just like in the last videos I'll use this request dummy API here to get a list of users and to also send a post request to fake registration now it's a fake API no real data is exchanged data you send to the server also isn't stored there but it's a great API for playing around with HTTP requests and experimenting with these features so let's start by sending a get request with the help of Axios because i'm importing it with a CDN here we have a globally available Axios object now I can just access it like this of course you find a full documentation on the official get up page and we can send a get request by calling the get method on access now this get method takes the URL to which you want to send a get request and then it returns a promise where you can listen to this case and to fail your case now the URL is the same URL I used in the other videos this is my get URL so I'll copy that and now just send my request to that URL now no additional configuration is required here though if you want to additionally configure the request you could absolutely do that you can pass in a second argument which is a JavaScript object that it takes certain options which you find described in detail on the official Docs of course where you can find you in the request to your requirements here I'll just send it like this though and now in the then block here we can work with the response and actually here let's see what we get let's console.log response here and save that and now reload our little application here and click get data now what you see is we get this object this object holds some information about the response for example the status code information about the request which was sent the headers that were part of the response and all the very important of course the data now unlike with the fetch API data is no streamed data which we manually have to converge to a snapshot like we did it here instead it's already the parsed and converted object it's no json data which we have to parse manually it's no stream data which we have to turn into a snapshot it's normal JavaScript data a JavaScript object we can work with so that's pretty convenient with axis we already got everything we need in this ven block and therefore sending the cat request is already done at this point now let's do the same for posting data again we can use access and now the post method there now previously in the other Tube videos I created utility functions send HTTP requests which would wrap the fetch API or XML HTTP request I did this to avoid code duplication with axis we don't really need that because axis already is the utility function or the utility object we're utilizing so there's little we could gain by wrapping this and yet Navarrete ility function instead we already are using get here which is pre-configured for gat requests and post here which is pre-configured for post requests now the post method also takes a URL twitch you want to send the request and here I want to send a request to this register API here so it's slash register at the end it's instead of slash users and of course now I also want to append data now Forex is on a post request to append a that we simply pass in a second argument this second argument is a JavaScript object which will automatically be converted to JSON data by axis so by the library and which will then be appended to the outgoing post request so therefore here I want to append a JavaScript object and now it's important that you append the right data for this dummy API otherwise the dummy API will give you an error and that's the data you also found in the dummy API Docs here essentially it's this email password pair here so I wanna append that here however of course all converted to regular JavaScript object we don't need quotes around email and password and with dead we're sending a post request so let's check the response here and console.log response here to see whether that works if we save that and we go back to our page here reload it and post data that's looking good we got a 200 status code and data is indeed signaling that yeah it worked this is some dummy data the API returns for a pseudo successful user registration not really a registration because it's all just dummy API but it worked now one important note if we have a look at the network tab and we have a look at the outgoing request then we see that actually the content type application Jason header was automatically added by axis so what axis does is it analyzes the data you're appending and then does the right thing with it for a JavaScript object it can it's a to Jason and it also adds the right header if we would have passed different data here let's say just some text here and I try to send a request with that then I actually get back an error response but if we check the network tab and there the headers we see that the content type was set to something different and we didn't add JSON data but form data so Axius is really smart regarding the data you append and it analyzes the day that you append and then converts it correctly and sets the right headers for the outgoing requests so we don't need to configure the headers manually here of course you still could do that if you wanted to you can pass a third argument to post get and so on which is an object that allows you to configure the request and there you can add a headers key which just like in the case of the fetch API is an object where you can add your own headers like this year so you can override this default or add other headers that is absolutely possible as you see if I reload here if we inspect the outgoing request now it has my own content type header but of course for just the content type you don't really need that because access is pretty smart about that now what about errors that was a bit tricky with both the XML HTTP request but also especially with the fetch API where we needed this inner wrapped API promise chain here to properly handle errors and get the error response body how does this work for Axios let's say we're sending a request to register but we're omitting the password and therefore the API will throw an error now let's add a catch method here and catch any error we might be getting and let's then console lock that error to the console to see whether we make it into this block that was not the case with the fetch API for example there we always ended up in a success block by default and if we do make it in there let's see what's inside the error object or string or whatever we're getting so if we save that and we now post here we see we're getting back this output here now it's coming from line 28 in my script and that indeed is the right line that is my error handling block so an important takeaway is that X is automatically throws an error if the response has a error status code so it does not just throw errors if you have a technical error let's say connectivity issues but also if you have a technically successful response that has a 400 or 500 status code though and that's a major difference compared to the fetch API and xmlhttprequest there if we had a technically successful response which just had a error or a status code so a 400 dish or 500 ish status code we would always make it into the success handlers and then we manually had to check the status code there and make sure we throw an error maybe parse the error response and so on axis is different for error status codes it automatically float throws an error so that we automatically end up in our catch block here now to learn more about the air or response though and for example get its data we can access a response property on this error object and if we do it cell and post the data you see we get our normal response object with the response data which in this case holds the error description so that's useful for getting the body off the response even if it had a status code of 400 or 500 or whatever it is and that's therefore Axios now you can probably see that working with access is really straightforward which is why it is very popular and often used instead of XML HTTP request or a fetch actually I'd say XML HTTP request is rarely used like this because it requires a lot of overhead setup and here I'm just covering some basic cases we're not doing anything complicated here the fetch API is a bit more popular to be used just as it is but more complex your application gets the more important error handling is and so on the more inconvenient it can get to work with it and therefore axis is quite popular because there you almost get the best of both worlds you get a promise based API and still a lot of the heavy lifting is taken away from you you get convenience methods for sending get and post requests and error handling just works so therefore of course it's totally up to you to work with whatever you want or need in your projects but giving axis a chance or considering axis over the fetch API or xmlhttprequest might be worth it and that's it this was the last video in this short mini series of sending HTTP requests from a client-side JavaScript application to a server I hope it was helpful I hope you now have a basic understanding of the options you have how they compare and how they generally work of course you can always do way more with each option than what I showed you here this was just a basic introduction and comparison the documentation you'll find on pages like mdn or in the case of x yes the official access talks is of course a great place to dig deeper nonetheless this hopefully was helpful and helps you in your next project to choose the right option and most importantly to also use it successfully
Info
Channel: Academind
Views: 92,832
Rating: undefined out of 5
Keywords: axios, javascript, ajax, ajax requests, javascript http, js http, js axios, javascript axios, http axios, js fetch, javascript fetch, xmlhttprequest, tutorial
Id: qM4G1Ai2ZpE
Channel Id: undefined
Length: 13min 13sec (793 seconds)
Published: Mon Sep 23 2019
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.