Open In App

Getting error handler data from post request in AXIOS

Improve
Improve
Like Article
Like
Save
Share
Report

Axios is a JavaScript library that creates HTTP requests using either XMLHttpRequests in the browser or HTTP in the Node.js runtime by using the Promise API. These requests can use async/await syntax and can also use the .then() utilities for promise chaining, and the .catch() mechanism for error handling because these requests are promises. 

In this article, we are going to discuss how to handle errors from POST requests in AXIOS. There are two approaches to handling the error of post request in AXIOS:

  1. Async/Await Method
  2. Then and Catch Method   

Before start discusses or implements these above approaches, let’s set up our project and install some dependencies as well. Use the below commands or steps for creating Nodejs Project for implementing these approaches. 

Step 1: Create One Folder and open the folder in the command prompt. Use this command for initializing that folder.

npm init -y

Initializing Project

Step 2: Now, Install two important dependencies. First, Axios for making requests, and Second, Express for creating and running the server.

npm install axios express

Step 3: Create one Javascript file named app.js. In this file, we will be writing our code. Now, the Project Structure will something look like this.

Project Structure

Approach 1: Using Async/Await

Now, Let’s discuss the first approach to handling errors using Async/Await Method. Before starting implementation, let’s understand about async/await method. The await keyword is allowed in the function body when using the async function declaration to declare an async function. The async and await keywords make it possible to write promise-based, asynchronous behavior in a cleaner manner without having to explicitly configure promise chains.

Syntax:

app.get('/endpointURL', async (req, res) => {
 try {
     const result = await axios.get('/api-url');
       // Work here with result
 } catch (err) {
     // Error handling here
    return res.status(401).send(err.message);
 }
})

Implementation: It is simple to send a configuration object to the Axios function to send an HTTP request. Using Axios, we may send a POST request to send data to a certain endpoint and start events. Call axios.post() to send an HTTP POST request using AXIOS. The URI of the service endpoint and an object containing the properties we want to send to the server are required when making a POST request in Axios. 

Syntax of POST Request of AXIOS:

axios.post(url[, data[, config]])

Also, we are using try and catch block for handling errors. We can specify a section of code to be tested for errors as it is being performed using the try statement. We can specify a block of code to be executed if an error occurs in the try block using the catch statement.

Try and Catch Syntax:

try {
    // Our Request Code
}
catch(err) {
    // Error Handling code
}

In try blocks, we have one payload object with some values and we want to post this payload object using a post request through Axios. We are using the Async function for making asynchronous requests and Await keyword for making requests in waiting for the state until the request returns some response. Once the request returns some response, we will store it in the result variable. If there is any error in a request that error will get handled in the catch() method. 

File: app.js

Javascript




const express = require("express");
const axios = require("axios");
const app = express();
const port = 8000;
  
app.get("/postRequest", async (req, res) => {
    try {
        payload = {
            name: "New Demo Airlines",
            country: "Demo",
            logo:
            slogan: "From Demo",
            headquarters: "State, Demo",
            website: "www.demo_website.com",
            established: "2000",
        };
        const result = await axios.post(
            payload
        );
        res.send(result.data);
        // Work here with result
    } catch (error) {
        if (error.response) {
            // If server responded with a status code for a request
            console.log("Data ", error.response.data);
            console.log("Status ", error.response.status);
            console.log("Headers ", error.response.headers);
        } else if (error.request) {
            // Client made a request but response is not received
            console.log("called", error.request);
        } else {
            // Other case
            console.log("Error", error.message);
        }
        // Error handling here
        return res.status(401).send(error.message);
    }
});
  
app.listen(port, () => {
    console.log(`Example app listening on port ${port}`);
});


Output: In Output, First, we are successfully creating post requests using AXIOS. After creating a successful request, we are changing the valid URL to an Invalid URL which will create a 404(Not Found) error which gets handled by the first if-else condition. 
 

 

Approach 2: Using Then and Catch Method

Promise chains are excellent at handling errors. The then() method is invoked if a promise is successfully resolved. The control switches to the closest catch() error handler method when a promise rejects. No immediate action is required from the catch(). After one or possibly more then(), it might appear.

Syntax:

axios.get('/api-route-url')
    .then(result => {
        // Work here with the result
    }).catch(err => {
        // Error Handling here
        return res.status(401).send(err.message);
})

Here, In this implementation, We are using then and catch methods for handling responses and errors. If our request is successfully executed without any errors, then we will handle it in the then() method. If there is any error occurred in the request, then it will get handled in the catch() method. 

File: app.js

Javascript




const express = require("express");
const axios = require("axios");
const app = express();
const port = 8000;
  
app.get("/postRequest", (req, res) => {
    payload = {
        name: "GeeksforGeeks",
        country: "India",
        logo: 
        slogan: "From India, With Love",
        headquarters: "Delhi, India",
        website: "www.geeksforgeeks.org",
        established: "2000",
    };
    axios.post(
        payload
    ).then(result => {
        // Work here with the result
        res.send(result.data);
    }).catch(error => {
        if (error.response) {
            // If server responded with a status code for a request
            console.log("Data", error.response.data);
            console.log("Status", error.response.status);
            console.log("Headers", error.response.headers);
        } else if (error.request) {
            // Client made a request but response is not received
            console.log("<<<<<<<Response Not Received>>>>>>>>");
            console.log(error.request);
        } else {
            // Other case
            console.log("Error", error.message);
        }
        // Error handling here
        return res.status(401).send(error.message);
    });
});
  
app.listen(port, () => {
    console.log(`Example app listening on port ${port}`);
});


Output:

 

It should be noted that while both of these methods are capable of producing the same functionality, async/await is frequently preferred because it can handle longer promise chains easily.



Last Updated : 19 Dec, 2022
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads