Introduction

A web application often needs to communicate with web servers to get various resources. You might need to fetch data from or post data to an external web server or API.

Using client-side JavaScript, this can be achieved using the fetch API and the window.fetch() function. In NodeJS, several packages/libraries can achieve the same result. One of them is the [node-fetch](https://www.npmjs.com/package/node-fetch) package.

node-fetch is a lightweight module that enables us to use the fetch() function in NodeJS, with very similar functionality as window.fetch() in native JavaScript, but with a few differences.

Getting Started With node-fetch

To use node-fetch in your project, cd into your project directory, and run:

$ npm install node-fetch

To use the module in code, use:

const fetch = require('node-fetch');

As previously mentioned, the fetch() function in the node-fetch module behaves very similarly to the native window.fetch() function. Its signature is:

fetch(url[, options]);

The url parameter is simply the direct URL to the resource we wish to fetch. It has to be an absolute URL or the function will throw an error. The optional options parameter is used when we want to use fetch() for anything other than a simple GET request, but we will talk about that more in-depth later.

The function returns a Response object that contains useful functions and information about the HTTP response, such as:

  • text() - returns the response body as a string
  • json() - parses the response body into a JSON object, and throws an error if the body can’t be parsed
  • status and statusText - contain information about the HTTP status code
  • ok - equals true if status is a 2xx status code (a successful request)
  • headers - an object containing response headers, a specific header can be accessed using the get() function.

Sending GET Requests Using node-fetch

There are two common use cases of fetching data from a web server. You might want to retrieve text from the web server, a whole web page, or data from using REST API. The node-fetch package allows you to do all of that.

Create a directory for your project, cd into the directory and initialize a Node project with default settings:

$ npm init -y

This will create a package.json file in the directory. Next, install node-fetch as shown above and add an index.js file.

Fetching Text or Web Pages

Let’s make a simple GET request to Google’s home page:

const fetch = require('node-fetch');

fetch('https://google.com')
    .then(res => res.text())
    .then(text => console.log(text))

In the code above, we’re loading the node-fetch module and then fetching the Google home page. The only parameter we’ve added to the fetch() function is the URL of the server we’re making an HTTP request to. Because node-fetch is promise-based, we’re chaining a couple of .then() functions to help us manage the response and data from our request.

In this line, we’re waiting to receive the response from the Google web server and converting it to text format:

.then(res => res.text());

Here we’re waiting for the result of the previous conversion and printing it to the console:

.then(text => console.log(text));

If we run the code above from the console:

$ node index.js

We’ll get the entire HTML markup of the Google home page logged to the console:

<!doctype html>
<html itemscope="" itemtype="http://schema.org/WebPage" lang="en-RS">
    <head>
        <meta charset="UTF-8">
        <meta content="origin" name="referrer">
        <!-- Rest of the page -->

#javascript #node #http #tool

Making HTTP Requests in Node.js with node-fetch
1.20 GEEK