Today I am going to be discussing how Axios can be utilized as a efficient tool for sending data to the server-side from the client-side and how to obtain information gathered back from RESTful API’s. Let’s get started.
What is Axios?
In order to install Axios locally, you must first have npm installed onto your machine. Let’s say for the purpose of this blog, NPM is already installed. In this case, you can just issue the terminal command below to install.
npm install axios
Importing into a file:
const axios = require(‘axios’); //importing into a node environmentimport axios from ‘axios’; //importing in a client-side module
Before we dive any deeper into this blog, first we should get to know the basics of what Axios can do.
Making a basic GET request:
Above is a bare-bones example of how a get request looks while using Axios. On line 3 inside of the arg, the string would be the link to the website you want to obtain data from (this could also be localhost) and on line four within the scope of this then block you will be able to access your data from the request and do anything you would like with it.
Making a basic POST request:
In this visual depiction above, the structure looks similar, but the behavior is entirely different. Notice how on line 3 now there is an additional argument with an object inside. This object is what will be sent to the server via your POST request, and it is important for this object to be in a JSON format. The then block on line 4 will now be able to return the OK, ensuring that what data is being sent to the server is the correct data, and will be logged as the ‘result’ parameter.
Making a basic PUT request:
In the almost identical structure to the POST request, the PUT request will be sending data to the server, and will be able to change the contents of a stored value in the database. Normally this feature is built within the website’s server-side PUT request.