Getting to Know the In-s and Out-s of Axios

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?

Axios is known for being a Node package designed to make HTTP request easier through using bluebirds, “Javascript promises” to asynchronously send/receive data from HTTP requests. The place where Axios primarily shies the most, however, is making RESTful requests to either an API to send/receive data, or to pass data from the client-side environment to the server-side.

The Basics:

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.

Installation:

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.

JS Dev

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store