← coderrocketfuel.com

Make an HTTP POST Request With Node-Fetch & Node.js

How do you make an HTTP POST request using the Node-Fetch NPM package and Node.js?

In this article, we'll show you how you can achieve that.

There are a lot of ways to make an HTTP POST request in Node.js, but using the Node-Fetch NPM package is one of the easiest ways to do it. The package is a light-weight module that brings the browser window.fetch method to Node.js.

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

NPM:

npm install --save node-fetch

Yarn:

yarn add node-fetch

When that's done installing on your machine, it will be available to require() into your Node.js application.

Open a Node.js file in your favorite text editor and add this code to it:

const fetch = require("node-fetch")

const body = {
  title: "foo",
  body: "bar",
  userId: 1
}

fetch("https://jsonplaceholder.typicode.com/posts", {
  method: "post",
  body: JSON.stringify(body),
  headers: { "Content-Type": "application/json" }
})
.then(res => res.json())
.then(json => console.log(json))
.catch(err => console.log(err))

Let's go through each part of the code.

The first thing we do is require() the Node-Fetch NPM package and assign it a variable name of fetch to use in our application.

Then we create an object called body that holds the data we will include in our POST request. This includes the title, body, and userId items.

Next, we use the fetch() function 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 want to make the request to.

The second parameter to the fetch() function is an object with these items in it:

  • method: the type of request we're sending (POST in this case).
  • body: a JSON.stringify version of our body object we created earlier in the code.
  • headers: the header data we want to put on our request.

Node-Fetch is promise-based, so we use a series of .then() functions. The first one waits for the fetch() function to receive a response from the URL it made the request to and converts the response into a JSON format for easy consumption. And the second one waits for the JSON data to be provided and logs the data when it's received.

There's also a .catch() function that logs an error if one occurs during the course of the fetch() function or its subsequent .then() promises.

When you run the code, your output should look similar to this:

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

The fake data from the JSON Placeholder API is returned as a result.

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

Thanks for reading and happy coding!