Onjsdev

Share


Axios Post Request | axios.post()


By onjsdev

Jul 18th, 2024

Axios is a popular javascript library for making HTTP requests both in web browsers and Nodejs environments. It provides a simpler approach compared to traditional fetch API.

On the other hand, a POST request is essentially a way to submit information to a server on the web. In Axios, you can easily send a POST request using the axios.post method.

Here's how it works:

How To Install Axios

First, you'll need to include Axios in your project. This can be done through various methods like CDN links or package managers such as npm or yarn.

npm i axios

How To Make An Axios POST Request

Next, you can make the POST request using the axios.post() method. In the basic usage, this method takes two arguments: the URL you want to send the request to and the data you want to send.

The data can be in various formats, such as JSON, URL-encoded form data or plain text.

Here's an example:

axios.post('https://api.example.com/users', {
  name: 'John Doe',
  email: 'john@example.com'
})
  .then(response => {
    console.log(response.data);
  })
  .catch(error => {
    console.error(error);
  });

Here, the .then method is called if the request is successful, and if it exist, the response object contains response message in the response.data property, while the .catch method handles any errors that might occur during the request.

How to Send Headers with Axios Post Request

In addition to sending data to a server, you may often need to include headers in your POST requests. Headers provide additional information to the server, such as authentication tokens, content types, or custom metadata.

To include headers in your POST request with Axios, you can pass an optional headers object as a third parameter to the axios.post method. The headers object should contain key-value pairs representing the header names and their respective values.

Here's an example:

axios.post('https://api.example.com/users', {
  name: 'John Doe',
  email: 'john@example.com'
}, {
  headers: {
    'Authorization': 'Bearer token',
    'Content-Type': 'application/json'
  }
})
  .then(response => {
    console.log(response.data);
  })
  .catch(error => {
    console.error(error);
  });

In this case, the headers object contains two headers: Authorization and Content-Type. You can add any number of headers as per your requirements.

Conclusion

In conclusion, Axios provides a simple API for making any type of HTTP requests. When you want to post data to an API, Axios provides a clear interface for working with POST requests.

Thank you for reading.