Getting error handler data from post request in AXIOS
Last Updated :
05 Aug, 2024
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:
- Async/Await Method
- Then and Catch Method  Â
Before start discusses or implement 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 ProjectStep 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 StructureApproach 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:
"https://media.geeksforgeeks.org/wp-content/cdn-uploads/gfg_200x200-min.png",
slogan: "From Demo",
headquarters: "State, Demo",
website: "www.demo_website.com",
established: "2000",
};
const result = await axios.post(
"https://api.instantwebtools.net/v1/airlines",
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:
"https://media.geeksforgeeks.org/wp-content/cdn-uploads/gfg_200x200-min.png",
slogan: "From India, With Love",
headquarters: "Delhi, India",
website: "www.geeksforgeeks.org",
established: "2000",
};
axios.post(
"https://api.instantwebtools.net/v1/airlines",
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.
Similar Reads
How to handle data fetching in React-Redux Applications ?
Data fetching in React-Redux applications is a common requirement to retrieve data from APIs or other sources and use it within your components. This article explores various approaches to handling data fetching in React-Redux applications, providing examples and explanations for each approach.Table
4 min read
How to Resolve form-data is getting undefined in Node/Express API ?
Working with forms and handling data submissions is a basic requirement in web development. When using Node and Express for building APIs, you might get an error that the FormData object is undefined. In this article, we'll explore how to resolve form data getting undefined in a Node/Express API. Th
3 min read
How to create a new request in Postman?
Postman is a development tool that is used for testing web APIs i.e. Application Programming Interfaces. It allows you to test the functionality of any application's APIs. Almost every developer uses Postman for testing purposes. We can create any type of HTTP request in it such as GET, POST, PUT, D
2 min read
How to resolve req.body is empty in posts error in Express?
In Express the req.body is empty error poses a critical challenge in web development, particularly in the context of processing POST requests on the server side. This issue arises when the server encounters difficulties parsing the request body, resulting in an empty or undefined req.body object. De
4 min read
How Are Parameters Sent In An HTTP POST Request?
HTTP POST requests are widely used in web development to send data from a client to a server. Whether you're submitting a form, uploading a file, or sending JSON data via an API, understanding how parameters are sent in an HTTP POST request is important. In this article, weâll explore how are parame
4 min read
Flask HTTP methods, handle GET & POST requests
In this article, we are going to learn about how to handle GET and POST requests of the flask HTTP methods in Python. HTTP Protocol is necessary for data communication. In the context of the World Wide Web, an HTTP method is a request method that a client (e.g. a web browser) can use when making a r
6 min read
How to create and send GET requests in Postman?
Postman is an API(application programming interface) development tool which helps to build, test and modify APIs. It has the ability to make various types of HTTP requests(GET, POST, PUT, PATCH), saving environments for later use, converting the API to code for various languages(like JavaScript, Pyt
1 min read
How to Handle a Post Request in Next.js?
NextJS is a React framework that is used to build full-stack web applications. It is used both for front-end as well as back-end. It comes with a powerful set of features to simplify the development of React applications. In this article, we will learn about How to handle a post request in NextJS. A
2 min read
How to Get POST Data in Node ?
Handling POST data is a fundamental aspect of developing web applications and APIs using Node.js. POST requests are used when a client needs to send data to the server, such as submitting form data, uploading files, or sending JSON payloads. This article will cover various methods to retrieve and ha
4 min read
Get the Data Received in a Flask request
In this article, we will learn how we can use the request object in a flask to Get the Data Received that is passed to your routes. and How To Process Get Request Data in Flask using Python. So, basically, Flask is a web development framework written in Python, and flask is widely used as a web fram
6 min read