Using Axios In Javascript
In javascript, and in programming in general, one of the most important techniques to become familiar with is receiving data stored in one place, whether it be an outside database or an api, then bringing into your program and manipulating it as you please. In most javascript courses, this is taught using a fetch request, or the .fetch() function. This function grabs, or fetches, the data you are trying to receive from a URL that is passed in as an argument. So if we wanted to grab data from, let’s say, an api for a social media site, we would do something like:
Which would return to the console:
This is great, but serves us no purpose in our front end javascript application. In order to make this data useable we need to take it one step further, with the .json() function, which turns our data in to Javascript Object Notation.
Which would then give us:
Would you look at that. With a simple function we now have access to all the users in our API and can do whatever we please with them, but what if this was even easier…
Enter Axios
Axios is a promise based HTTP client for the browser and node.js. It behaves almost identically to fetch, but it saves us from using the .json() method. It may not seem like much, but as programmers we are trained to write as little code as possible, even if it is just one line. So, in the case of our user API, we can write:
This will return our JSON object from above.
Axios also allows us to control cookies with our network requests. By default, fetch requests do not allow cookies, but with Axios, we can change that with the withCredentials parameter like so:
Now we are enabling cookies in our request, which can be used for tracking data as our user navigates the web, creating a more personal experience for whoever is using our application.
This was just a simple introduction to Axios. If you are wanting to take a deep dive, there are plenty of resources to teach post requests, which can open up all kinds of new doors, as well as other parameters that can be passed in as well.