Axios Crash Course | HTTP Library

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
[Music] hey what's going on guys welcome to my Axios crash course so Axios if you've never heard of it which I'm sure most of you have but if you haven't it's an HTTP library or an HTTP client to make requests to either your own back-end or third party API to fetch data and it's similar to the fetch API which is built into the browser but I prefer it because I think it's it's more powerful and I like the syntax better so that's what I use if I'm building a react full-stack react or view app or vanilla JavaScript and I need to communicate with my back-end you can also use it with nodejs so it's it's a pretty popular tool and I use it in in many videos and courses but I never made a video dedicated to Axios so I figured I'd do that all right now instead of just doing a bunch of console logs we're going to use this interface here which has a bunch of buttons to do different things so for instance to make get post request put patch we're gonna look at making simultaneous requests with Axios dot all we're gonna look at custom headers transform responses error handling cancel tokens things like Global's and interceptors so we're gonna kind of dive deep into Axios in this crash course and just to give you an example if we make this get request here when I click this we're actually going to show the response in the body so we have a status of 200 our headers our data and config and we're going to be using the JSON placeholder fake REST API for our data so basically we can make requests to get in our case we're gonna use two Do's and we can make get post put patch and delete requests okay so that's we'll be using for our data this is the Axios github page which you might want to look at basically you can you can install it with NPM or yarn but we're gonna be using the CDN just with a front-end javascript file and as far as the requests they all return a promise so we're gonna use the dot then dot catch syntax but if you want to use a sink await you certainly can I just didn't add that on top of everything else all right so I will have a github repo in the description that's gonna have three files it's going to have an index.html start dot J s and an empty main dot J s or actually it probably won't include the empty file but the start dot j s is basically going to have just our event listeners that are going to listen on these buttons right here you can see each one has an ID and then we also have this div with the ID of res that's where our response is going to go and we have a function called show output that takes in a response that simply shows the status the headers the data and so on so we'll be using this within our other functions now all the functions that these event listeners are hooked up to like get to dues add to do custom headers all this right now they're just all console.log as you can see so that's where we're going to add all of our functionality that has to do with Axios so what I'm gonna do and what I would suggest you do if you're following along is just grab everything and start J s create a main J s and just paste that in alright because in our index.html we're including the Axios CDN and a main dot J s alright so we'll just go ahead and open this up with live server and open up our console and now if I click any of these you'll see get request posts so all of these should just console.log for now just some text alright so we're gonna start off with our get post put patch delete request and start off with get so let's jump into main J s can close up start J s now and go up to get to dues because we're gonna make our get request so there's a couple ways to make get requests I'm going to show you both ways so basically we can do Axios we have access to Axios because of the CDN we included and we can pass in an object and then the method we want to use so the method in this case is going to be a get request of course we could do post put or whatever and then URL this is the basically our back-end or the API we want to hit which in our case is going to be this JSON placeholder API so I'm going to use two Do's but you could use whatever you want so I'll just grab this URL because we're gonna get this data right here and paste that in okay so this is going to return a promise so we want to add on a dot then okay we'll put on the next line like that and then this will give us our response and as far as our response for now let's just do a console log of the response okay and then for error handling with promises I'm sure a lot of you know this but for those of you that don't you can add a dot catch which will catch any errors if something goes wrong and then you can handle those in this case let's just do a console error of the error object alright so we'll save this and this should actually make a request so let's jump back into our little interface here and click get and let's see what we get in the console all right so you can see we get a few different things we get a config object which has a bunch of stuff in it this is this is basically the config that was provided for the request and we get things like the method the URL there's some security stuff you can see those these tokens for cross-site forgery the headers so we have the request headers here or a response though this is the request headers and then we have data of course which is probably what you're going to be looking for most of the time you can see this is an array of all of the to Do's that we fetched all right so res dot data is always going to be your data that's returned and then we have our headers here our response headers content type cache control stuff like that and then requests this is basically just the request that generated this response in the browser it's going to be XML HTTP request xhr if you're using nodejs this will be the client request instance and then we have our stat 200 of courses successful or okay and then status texts in this case there's none all right so that's what this gives us what res gives us and of course if we wanted to access just our data we could just do res dot data and if we do that then we just get our data which is 202 dues all right so instead of doing just console logs we're gonna use our show output method right our show will put output function which takes in the response and then it will actually take the res elements in our HTML and insert this stuff here all right so let's just replace let's just pass in res and let's replace our console log with show output I'm just figured it'd be a little more interesting than just using the console so now you can see we get our status our headers data basically just all the stuff I just showed you in the console and then down at the very bottom we have our config now I want to show you how we can limit this data with this API we can pass in a URL parameter score limit equals 5 or whatever however many you want and it will limit that that to dues so in our request what we could do here is pass in show you a couple ways to do this we could pass in params and then we could say underscore limits and set that to 5 so basically this is just any URL parameter you want to add so if we save this and then we run this get again I'm just going to close that one up so if we run this yet again you'll see that we only get 5 back ok or 5 listed here which is what I want now we can shorten this up this is kind of a long way of doing it so I'm gonna go ahead and just copy this and then comment this out so you still have it and we can basically with Axios we can attach dot and then the method so get post put whatever we want so let's say Axios dot get and then just pass in the URL so I'm gonna just replace all of this with just the URL and then for the params for the limit we could do this so we could say params and then set that to you know underscore limits five so we can still add stuff like this that should work let's try it yeah so it still limits it to five but to make it even shorter we can just put this in the URL so we'll just get rid of that and we'll just put question mark underscore limits equals five and you can see this is a lot shorter than this up here and in fact since we're making a get requests we don't even need to do dot get if we just do Axio so it's gonna be a get request by default so you can see we get the same exact thing all right now even though we don't have to put dot yet I always do just because I think it's cleaner and it's just it's more descriptive it you just know it's a get request so I always do dot get even though you don't have to all right so that's basically a you know a simple request so let's make a post request let's add it to do which obviously involves you know sending data so again we could do it this way yeah I guess I'll just show you that real quick so I'm just going to copy that and then paste that in here and let's uncomment that so we could do post and then we're gonna make a request to this same URL we don't need params however we're sending data so we do need data and as far as the data goes there's a title so we'll say new to do and let's say completed I'll say completed false and the reason I'm adding this data is because if you look at what we get back we get title completed ID which is generated on the server automatically when we submit and then we also have this user ID which I'm just ignoring alright so this should give us a give us a response with this data plus the ID it's generated on the server just like a real API so let's save this and let's go back and hit post and you can see we get our response back and if we look at data we have our title new to-do completed false and it generates an ID of 201 and the reason its 201 is because there's 200 on the server which you can see where is it if we make our get request right here total count 200 so the next one we add is gonna be 201 for the ID all right you can see down here our headers so that made a post request now we can of course shorten this up let's just take the URL and let's go ahead and just say Axios dot post cause we're making a post request and then for the data we can just simply pass in as a second parameter an object with you know title nu to do and then completed false and that should do the same thing just make our request so you can see our data we get back need to do false 201 all right so that's a post request now for an update we can use either put or patch now the big difference between the two put is usually meant to replace the entire resource where patch will kind of update it incrementally and I'll show you an example of both so I'm just gonna actually copy this here and put this in update to do and let's make a put request okay so now when we make any kind of update or delete we need to know which to do we're actually dealing with so if we look at our API here and every API is different but let's look at this fake Jason right REST API so if we make a put request or patch or delete we need to include the ID in the URL alright so let's just say to do slash 1 which means we're updating the I to do with the ID of 1 and then same thing for the second parameter we're going to put in the data that we want to add so let's say updated to do and we'll set completed to true and let's save that and run it ok so if we go back to the put patch button which right now is making a put requests you can actually see that down here method put so we get updated to do completed true ID 1 now notice the user ID is gone because these two dues they do have user IDs now what we did is we basically just replaced this whole thing that's how this API works and how it should work when you make a put request if we make a patch request let's go ahead and do that I'm just going to change this to patch and save and then click this and now notice that our data includes the user ID because it didn't completely replace it all it did was replace what we specified which was the title and completed and of course ID is gonna stay the same ok if we look down in our headers we can see the method of patch ok so hopefully that makes sense now let's do the delete which is pretty similar pretty easy so I'm just going to grab this and paste that in and we're gonna make Axio scott delete to to do slash 1 and then we don't need to pass any data in because we're just simply deleting it and that should do it so let's save that let's hit delete and you can see that we made a delete request to this URL and we get nothing back in the data because we deleted the data so it returns just an empty object ok and obviously every backend every every API is can be different this one returns just an empty object alright so those are the basic you know get posed put watch and delete so now let's move on to some more interesting things so now I want to look at getting simultaneous data or making simultaneous requests I should say so let's say that we want to get if we look at our Jason placeholder here let's say we want to get both posts and two dues at the same time now we could make a request to get the posts and then inside the dot then we could make another request to get the two dues but that's not really the ideal way to do it so to wait on post and then get the two dues what we can do is we can use a method called Axios dot all which will actually take in an array of requests and then once all those requests are fulfilled all our I should say all those promises are fulfilled then we get our response and we handle it alright so let's try that out let's go to our get data function here and let's just get rid of this and we'll say Axios dot all and this is going to take in an array oops we want brackets here an array of requests so I'm going to do Axios dot get and actually it should be a comma let's put in here this will get to dues all right and then I'm gonna just copy this down and then we also want to get posts so down here we're going to put our dot then in our dot catch I'll just save her errors will just console error and then inside here we'll get our response and now what's gonna happen is we're gonna have two arrays I'm gonna just do a console log of res and then a first array which is obviously 0 and then let's also console.log res one alright and for our show output we can only show the output of one of these so I'll just do res let's do res one which is our posts and it goes in order this is going to be the first one so 0 this is going be the second one one and we could keep adding these as well we could make as many requests as we want and then this will only run when these are fulfilled so let's save this and let's go back and let's try sim requests simultaneous requests and you can see that two were made over here so if we look at these this one is the two dues the first one okay so here's our two dues and then if we look down here we get the posts we have a title a body and ID user ID all right so that's how we can make simultaneous requests now we can actually make this a little cleaner so instead of using R as 0 R as 1 we can use something called Axios dot spread which will allow us to give these variable names more descriptive variable names so in the dot then we can do Axios dot spread and this Axios thought spread takes in a function so we're gonna put in another set of parentheses and then we can give these variable names so to do's and posts and then this is going to be an arrow function and then let's just do will say show outputs posts okay but we also have access to to dues if we want to do something with those and it's in the same order so we have to do is is the first one so that's what you want to give this variable name so we'll save that let's see if we get our posts if we go to SIM requests and there we go you can see we get all of our posts actually we're getting like a hundred of them so let's just add the limit say limit equals five and limits equals five so now we should only get five of them good all right so what I want to talk about now and show you how to do is create interceptors which will allow us to basically run some kind of functionality we can intercept the request and run some kind of functionality like a logger so that's all I want to do is create a little lager for any requests that we make so let's go actually gonna go down to the bottom here because it's not going to be inside of a function it's just going to be right here so we can create an interceptor by doing Axios dot interceptors spell write interceptors dot request dot use all right so and here this takes a function with config as a parameter and we have access to anything in the config such as the method the URL stuff like that so what I'm gonna do is a console log with some backticks and let's get the method so we can get that with config dot method and then I'm just gonna add on to uppercase so that the method is uppercase t' and then let's just say request sent to and then we'll get the URL with the config parameter so config dot URL and let's put the timestamp we'll say at and then in an expression we'll say new date oops let's say new date and then dot get time so this will just give us a timestamp if you want to add a better formatted date you can and then we just simply need to return config all right and then if there's any error we can put in another parameter here another function with error and hopes and we just want to return here I want to return a promise dot reject and then pass in that error alright so we'll save that and now we should have a little logger every every time we make a request so let's hit get and over here on the console you'll see get request get request send - it should be sent get request sent all right sent - and then it has the URL so the Jason placeholder URL at and then the timestamp and again you can you know format this better if you want but every time we make a request if I do a post it tells us patch and if I reload this and I do a simultaneous requests we should see two of them okay because it made a request to not only the - duze but also the posts okay and it's the same exact timestamp because they got sent at the same exact time alright so that is interceptors so now what I want to look at is custom headers so let's go back up let's go right here to custom headers so a lot of times you'll have to send data in the headers a good example of this is when you have authentication with like JSON web tokens you might make a request to login you validate your login and then you get back a token and then you have to send that token in the header to access protected routes so the way we would do this let's actually just copy the post request yeah let's grab this post request right here let's say that you have to be logged in to create a post now what we would do here is create a config object and then here we create a headers object and any headers we want we could put here so if we want a content type for instance I could say content type and set that to application slash chasing because that's the type of data we're sending and then we might have an authorization header and in here we might have you know some some kind of token some JWT now down here we can pass the config in as a third parameter to act Axios dot post or put or whatever it might be so we have the URL we have the data we're sending and then the third parameter would be config so if we save this and we go back and we hit custom headers and we look at our response down in the config you can see the content type application Jason and our authorization which is would be some kind of token and then you would use this on your back-end ok so that's how you can send custom headers so the next thing we're going to look at our transform responses you can also do transform requests I haven't really used this much I don't think I've ever used it but I wanted to include it just because you can do it basically you can transform your requests or your response in certain ways so what I'm going to do is set a variable called options which I'm going to pass into Axios which is basically just going to make a get request to whatever I put in options and then let's show output of res alright so inside options let's say method post and of course we could just plug this right into here like we did above but I'm just kind of giving an alternate way this you know might clean clean it up a little bit so let's make a post request to our to do's and then let's see for the data that we want to send let's send a title of hello world and we can actually add this transform response now you want to basically take the default transform response and add to that rather than just overwriting it so you can do that with Axios defaults dot transform response and then dot concat and then this takes in a function with data as a parameter and then you have access to that data which would be this right here so let's say we just want to make this all uppercase in our response so I could say data dot title equals our data dot title dot to uppercase I mean this is pointless but it just gives you an idea of you know what this does so then we'll just return data so now if I save this and we call this function by clicking this button here you can see that in our data we get back hello world is all uppercase so just allows you to kind of tweak your response or your requests you can also do transform requests all right let's see let's take a look at Global's so with Global's you can actually make it so you can send a header value with every request and where this comes in handy is with tokens authentication tokens so I just showed you how to add a token to a custom header like this putting it in the config and then you know passing it into into the request now what if you have a whole bunch of protected routes you don't want to have to do this for every single one so what you could do is create a global so I'm going to go up to the top here and create a global for a token so we can do that let's put a comment let's say Axios Global's and we simply add to Axios defaults dots headers dot common you can put Global's in other places as well but this is probably the most common and then let's say we have authorization actually already did authorization let's do like X - off - token and actually want to set that equal to some token alright actually we'll get a real token let's just go to JWT io just to make it more realistic and we'll just grab this so you know jason web token would look something like this and we'll just put that right in there okay so you would get the token from the server after locking logging in you'd probably store it in local storage or something like that and then you could put it in a global and then if I make a request like any request even if I make this get request and I look in the config there's our token okay so if I make a put request there's our token so we could validate that on the server so that's you know really helpful alright let's see what do we want to do next let's take a look at error handling so right now up to this point we're just console dot erroring our errors and usually you know let's say you have a react app and you get a 404 error like something's not found on the server you might want to show a 404 page or do some kind of functionality based on that you know if you get a 400 response from form form validation you're gonna want to do something for that so in order to test that stuff out let's go down to it was error handling right here and let's get rid of that and let's just do a we'll grab the first request we made the get request simple grab that and put that in error handling okay so instead of just console error let's open up a block here now there's a few situations we might have so let's do an if statement and check for error dot response okay so what this means if this is true it means the server responded with a status other than the 200 range which is a success range okay so you can console.log error dot response dot data okay you may or may not have depending on the API and then we can get the status error response status and then if you want the headers you can also get those so let's just save that what I'm gonna do we'll get rid of this limit here and just add an S or just make this so it returns a 404 in this because this route obviously is not found so I'm gonna save this and then go back and hit error handling and notice over here on the console we get this 404 all right now in a lot of cases you might want to test for the stata actually it should have give us the headers to hmm oops didn't mean to do that let's see they do that all right error response hmm well yeah let's let's try this let's do if error dots response got status and let's see if that's equal to 404 and if it is let's just do an alert and let's say error page not found because you know 404 means not found and obviously if this is a real application like let's say a react app you would probably load not found component or something like that or not found page but let's see if that works so if we save that and we hit error handling yeah it's not working for some reason catch error oh I put out the word error why don't you guys tell me that all right so this should work there we go so now it's showing over here there's no error response data this is the error response status and the error response headers and since it's a 404 was seeing an alert that says page not found all right and then you could also do in else if you could check for error dot request and then what this means is the request was made but there was no response so I mean you could just I don't know console error error dot request like that all right so there's a few different situations and then maybe just doing else and then console error error dot message something like that so I mean it's up to you how you want to handle your errors but I'm just showing you what's available instead of just logging the error you might want your application to respond differently for different errors ok so now let's take a look at cancel tokens so we can actually cancel requests on the fly so right here let's get rid of this and let's actually make art let's make it get requests I'm just gonna grab this and put that there all right so right above here I'm gonna create a variable called source and we can set this to Axios dot uppercase C cancel token dot source all right and then what we want to do is in this dot get let's make sure that this says to do is correctly and we're gonna pass in here canceled token lowercase C and then set that to source dot token all right and then what we can do is add our let's see we'll just do our show output for the response but for the dot catch we can in here we can pass in thrown and we can say if Axios dot is canceled and then pass in thrown so if that's true then let's just do a console log and we'll say oops I'll say request canceled okay and then we'll pass in thrown dot message all right so if I save this and I go back and I hit cancel it just makes the get request as usual but let's say we had some kind of condition I'm just gonna say if true but for some reason if something happened and you wanted to cancel that request then you could do source dot cancel and we'll just pass in here request canceled and if we go back now and I hit cancel notice that it didn't even we didn't get a response back it was canceled okay so if for some reason you need to cancel a request so you can do that that's another thing that I really haven't dealt with but I did want to include in the tutorial all right so we're just about there the last thing I want to show you is that we can have instances Axios instances right now we've just been dealing with kind of I guess the global Axios object but what we could do let's go down here I forgot to add this in the start dodj a yes but let's say Axios instance and we can actually create a variable like Axios instance and we can set it to Axios and then there's a method called create okay so we could say Axios create and then we can actually have custom settings in here and one of which is the base URL so let's set the base URL to this right here but not the slash to do is just a type a code comm so I'm going to pass that in as the base URL alright and then what we can do is use that Axios instance this is just going to run right away but I'm gonna use Axios instance instead of just Axios and then make a get request all right and then in here I can just simply pass in let's get comments that's another resource we can get from Jason placeholder so we'll just do slash comments and I didn't have to add this because that's our base URL for this instance and then we can say dot then res and let's show output res and save and then right away right when we go what's this what I do wrong here see Axios instance get slash comments that should work I believe Axios create passing an object with the base oh its base URL all it's all caps alright let's try that and there we go so now you can see we're getting comments down here alright if we go down to the config here you can see Jason placeholder type e code slash comments okay so I mean you can create an instance and you can have there's other custom settings you know you can have other custom settings as well all right I'm just gonna comment that out so it doesn't run right away now there's just a couple other properties that I want to mention one is that you can actually set a timeout so let's actually go to our just go to the top requests that we made this get to do is right here and we can add in as a property here we can say timeout and basically this is like the the max time that we want it to take before it just stops so let's just put five which is five milliseconds so it's it so it's always gonna timeout so we're gonna save that and then try it out so if I hate get notice over here we get an error that says time out of 5 milliseconds exceeded okay so it just stopped even trying after five milliseconds so you might want to set that you know to I don't know five thousand milliseconds which is five seconds and then that you know should work it shouldn't take more than five seconds to get alright so you can set timeouts another thing I wanted to show you that has to do with error handling so if we go down to error handling right now it's gonna throw the catch error on any status but what we could do is we could say that we only want this to throw for certain statuses like above 500 which is a server status so we could set inside here set an object and we can use validate status which takes a function and takes in status and then here we can say return I will say return status that is less than 500 so what this will do is reject only if status is greater it'll actually be greater or equal to 500 all right so we'll save that and now even though this is wrong and it's gonna be a 404 it shouldn't it shouldn't run the catch so if I go back here and hit error handling we do get the 404 but we still everything still goes through when the catch doesn't run we just don't get the data because it's there's nothing there okay and we can see you know status 404 right here as well so if you only if you want to limit your your catch to a certain status you can do that but I'm just gonna comment that out alright so I think that's it I mean there's some other properties if you want to check the documentation out but I think we pretty much went over all of the really important stuff that you're gonna need to know in terms of especially in terms of front-end web development or for full stack development we're using Axios on the front end alright so that's it guys hopefully you enjoyed this and learn something from it and all the code is going to be in the description and the github repo and that's it thanks for watching
Info
Channel: Traversy Media
Views: 212,774
Rating: undefined out of 5
Keywords: axios, axios javascript, http, axios http, fetch api
Id: 6LyagkoRWYA
Channel Id: undefined
Length: 42min 20sec (2540 seconds)
Published: Fri Oct 25 2019
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.