How do you make an HTTP POST request in Node.js using the Axios NPM package?

In this article, we'll show you how to do that.

There are a lot of ways to do this in Node.js, but using the Axios NPM package is one of the easiest ways to do so. It makes requests where callbacks and async behavior are involved super easy.

You can install the Axios NPM package with either the NPM or Yarn command below:

NPM:
    
      npm install --save axios
    
  
Yarn:
    
      yarn add axios
    
  

Once that's done installing, you can use it in your Node.js project.

Open a Node.js file and add this code to it:

    
      const axios = require("axios")

      axios.post("https://jsonplaceholder.typicode.com/posts", {
        title: "foo",
        body: "bar",
        userId: 1
      }).then(function(response) {
        console.log(response.data)
      }).catch(function(error) {
        console.log(error)
      })
    
  

Let's go through each part of the code.

The first thing we do is require() the Axios npm package we installed as a dependency for our project.

Then we use the axios.post() method to make a request to the JSON Placeholder API that supplies fake JSON data for prototyping and testing applications. The first parameter is the URL we are making a request to and the second is an object with the data for our HTTP POST request.

Since Axios is promise-based, we use the .then() function to wait until the axios.post() method receives a response and logs the response data when it arrives.

And we also use a .catch() method to wait for an error to occur and log it if one shows up.

When you run that code, it should log something similar to this in your console:

    
      { title: 'foo', body: 'bar', userId: 1, id: 101 }
    
  

There you have it, that's how you make an HTTP POST request using the Axios NPM package!

Thanks for reading and happy coding!