Handling Response Data From POST Requests
Now let’s take the above example for understanding our response. Once an HTTP POST request is made, Axios returns a promise that is either fulfilled or rejected, depending on the response from the backend service.
- To handle the response, we can use then() method:
axios.post('/login', credentials)
.then((response) => {
console.log(response);
}, (error) => {
console.log(error);
});
- If the promise is fulfilled, the first argument of then() will be called; if the promise is rejected, the second argument will be called. We can also follow a try-catch block format.
{
// `data` is the response sent by the server
data: {},
// `status` is the HTTP status code from the server response
status: 200,
// `statusText` is the HTTP status message from the server response
statusText: 'OK',
// `headers` the headers that the server responded with
// All header names are lower cased
headers: {},
// `config` is the config that was provided to `axios` for the request
config: {},
// `request` is the request that generated this response
// It is the last ClientRequest instance in node.js (in redirects)
// and an XMLHttpRequest instance the browser
request: {}
}
- Axios automatically converts request and response to JSON by default, but it can also you to override the default behavior and define a different transformation mechanism. Some APIs accept formats such as XML or CSV and this feature can be very useful for that.
- To change request data before sending it to the server, set the transformRequest property in the config object. Note that this method only works for PUT, POST, DELETE, and PATCH request methods.
const options = {
method: 'post',
url: '/login',
data: credentials,
transformRequest: [(data, headers) => {
// transform the data
return data;
}]
};
// send the request
axios(options);
How To Use Axios NPM to Generate HTTP Requests ?
In this article, we are going to learn about Axios and HTTP requests and using Axios to generate HTTP requests. Axios is a promise-based HTTP library that is used by developers to make requests to their APIs or third-party API endpoints to fetch data. It is a popular JavaScript library used for making HTTP requests from web browsers and NodeJS applications. It provides a simple and intuitive API for performing asynchronous operations like fetching data from APIs, posting form data, and more.
Table of Content
- HTTP Requests
- Axios
- How does Axios work?
- Installing Axios NPM for Your Project
- Creating an Axios Instance With Default Settings
- Performing GET Requests With Axios
- Performing POST Requests With Axios
- Sending Data with POST Requests
- Handling Response Data From POST Requests
- Shorthand Methods for Axios HTTP Requests
- Error Handling With Axios
- Conclusion
Contact Us