Introduction to Axios for requests - 2

Introduction to Axios for requests - 2

Introduction

What is Axios?

Axios is a promise-based HTTP client for JavaScript. It can make HTTP requests and handle the transformation of request and response data.

Axios can be used on a node application or in a simple web app.

Let's get started

In this article, we will use Axios in a simple node application for POST requests, you can check out my piece for GET requests here. Start a project folder with an index.js file. Use the npm init -y command on your terminal to initialize the project.

Once you are done with the initialization, use npm install axios to install Axios on your machine.

Now, we are going to use this route for adding users to the database.

http://localhost:3002/addusers

This is the API that I created for adding the users to the database (This API is connected with the database), you can't use this exact address since it's the localhost which can be only used in the machine where the program for that specific route runs.

Make sure to include "type": "module" in the package.json file to avoid a syntax error.

POST Request

Arguments we need to add the user to the database

  1. username
  2. password

In the index.js file

import axios from 'axios';
const getResponse = (username, password) => {
    const credentials = {
        username : username,
        password : password
    }
    axios.post("http://localhost:3002/addusers", credentials)
    .then(res => {
        console.log(res)
    })
    .catch(err => {
        console.log(err)
    })
}
getResponse("Administrator", "Password@123");

Explanation

In the function getResponse(), we send the parameters that we need as the arguments to make the post request. Here, we are using the name "Administrator" as the username and "Password@123" as the Password, those values will get added to the database when we call the function the getResponse() if everything goes as we coded.

Code Explanation

We call Axios with the syntax of axios.post(URL). We can use methods of data communication by using get, post, patch, and so on then we use the URL from which the data communication should happen. We are passing the username and password information to the server by storing it in the variable called "credentials". The server would consider that informations as the request and would read them as req.body.username, req.body.password.

The statement ".then" would run strictly if only the request was successful. Data received is usually like a JavaScript object and can be stored in any name, above we used 'res'. If you print out res, the result would look like this Medium-Axios-2.png

Looking at the image, we can see that it has a status of 200 which means that the request was successful.

So, the program works just fine but getting this as a response doesn't do much for us. We have to extract the data that we need. Let's get back into the code.

.then(res => {
        console.log(res.status)
    })

Simply, by adding .status

with the help of objects, We can extract the status code of the response from the server, hence the output would be

200

This means as I said, the program worked just fine and the user "Administrator" was successfully added to the database.

Error Handling

The .catch statement would only execute if the request failed, this data can be logged into a console after being stored into a variable called 'err'.

So, the total looks like this

import axios from 'axios';
const getResponse = (username, password) => {
    const credentials = {
        username : username,
        password : password
    }
    axios.post("http://localhost:3002/addusers", credentials)
    .then(res => {
        if(res.status == 200){
          console.log("It works!")
        }
    })
    .catch(err => {
        console.log(err)
    })
}
getResponse("Administrator", "Password@123");

Now the user "Administrator" with the "Password@123" has successfully been added to the database. This is the actual backend work that takes place every time you register yourself as a new user on any sites that has user registration such as Instagram and Facebook. Of course, their implementation would contain lots of security layers to prevent the database from being hacked. We will look into one of the security layers that you can do while sending a request to the server called JWT in another article.

Conclusion

There are other methods such as put, patch, and delete. Each has its purpose, We will look into those in the upcoming article where we dive deep into the topic of how the developers work with Axios.