How to make HTTP GET Request in Node.js [Practical Examples]


NodeJS

Author: Steve Alila
Reviewer: Deepak Prasad

Introduction

There are several ways that you can make HTTP GET requests in Node.js. The GET method is used to request data from a particular resource. This article discusses the different ways you can make GET requests in NodeJS and provides practical examples.

 

Method-1: Using HTTPS Module

The first solution to making GET requests is using the http(s) module provided by Node.js. This module provides a variety of methods, one of them being GET.

If you would like to follow along with these examples, make sure you have NodeJS installed. If you don’t, use this NodeJS installation tutorial to set it up in your working environment.

Why HTTPS?

Assume you want to create a NodeJS server.

You can do that by making a file, get-request.js, and open it with your favorite text editor. Next, create a server by adding the following code.

const http =  require("http")

const server = http.createServer( (req, res) => {
    res.end("Hello, World!")
})

const PORT = process.env.PORT || 3000

server.listen(PORT, console.log(`listening on PORT ${PORT}`))

You then test the code by locally running the server with nodemon followed by viewing the response on the browser.

How to make HTTP GET Request in Node.js [Practical Examples]

You must have noticed I used http to create the server. That's fine when fetching data locally. However, you should switch to https when consuming APIs because most remote servers want to interact with your computer through SSL that comes with the Node.js https module.

So, let's change http to https before making GET requests to the API.

const http =  require("https")

This is the syntax for using the http(s) module for a GET request.

http.get(url, [options], [callback])

http.get()  accepts a URL which is a string, an object of options, and a callback function. http.get() returns http.ClientRequest()

For this tutorial, you will send your requests to the NASA photo of the day API.

In get-request.js, add the following code.

let url = 'https://api.nasa.gov/planetary/apod?api_key=DEMO_KEY'

http.get(url, res => {

    let rawData = ''

    res.on('data', chunk => {
        rawData += chunk
    })
    
    res.on('end', () => {
    const parsedData = JSON.parse(rawData)
    console.log(parsedData)
    })

})

In the above code, we start by first assigning the URL that will receive the request to the URL variable. Next, we call the https.get() method and pass in the URL stated and a callback function that will handle the response from the URL. If the GET request fails, the error message will be displayed on the console.

Inside the callback function, the data will be received in chunks. That is why we store every chunk in the rawData variable.

The next step is to parse the data once the request completes.

res.on('end', () => {
   const parsedData = JSON.parse(rawData)
   console.log(parsedData)
 })

How to make HTTP GET Request in Node.js [Practical Examples]

That’s how you use https to make GET requests. While this way of making GET requests works, it is very verbose. The solution is to use third-party packages like Axios, SuperAgent, and Unirest.

 

Method-2: Using Axios

Axios is a promise-based HTTP client that makes it easier to perform requests in NodeJS. Writing promise-based requests is beneficial especially when dealing with large blocks of data since the rest of your application can continue executing as you wait for the request to resolve.

To install Axios, run the following command in your terminal.

npm install axios

The above code can now be rewritten as shown below:

const axios = require('axios')

let url = 'https://api.nasa.gov/planetary/apod?api_key=DEMO_KEY'

axios.get(url)
  .then(res => {
    console.log(res.data)
  })
  .catch(error => {
    console.log(error)
})

We pass the url to axios which handles the request (with SSL implementations) for us. It returns the response, from which we get the data res.data and log to the console.

How to make HTTP GET Request in Node.js [Practical Examples]

As you can see the Axios implementation requires less code to make the HTTP get request and process the data. Also, note that we are not parsing the response. Axios does that for us. In case of an error, the catch block handles it.

 

Method-3: Using SuperAgent

Like Axios, SuperAgent is an API that provides a simple and flexible solution to making requests in NodeJS.

To rewrite the same request we have been making using SuperAgent, modify your request, as follows.

const superagent = require("superagent")

superagent
 .get("https://api.nasa.gov/planetary/apod")
 .query({ api_key: "DEMO_KEY" })
 .end( (error, res) => {
   if (error) {
     return console.log(error)
   }
   console.log(res.body)
 })

With SuperAgent you can add request parameters to the URL by chaining them through query(). The response body contains the data sent back from the API and can be accessed through res.body().

How to make HTTP GET Request in Node.js [Practical Examples]

 

Method-4: Using Unirest

You can also use another simple HTTP client library that allows node.js applications to easily make requests. The main difference between unirest and other libraries like axios and SuperAgent is that unirest is available in multiple languages such as JavaScript, Ruby, Java, and PHP.

const unirest = require('unirest')
unirest.get('https://api.nasa.gov/planetary/apod')
 .query({'api_key': 'DEMO_KEY'})
 .end((res) => {
   if (res.error) {
     console.log(res.error)
   } else {
     console.log(res.body)
   }
 })

Unirest also allows us to chain query parameters using query() instead of manually adding them to the URL you are requesting resources from.

 

Method-5: Using Fetch API

With the update of Node.js to version 17.5, you no longer have to install a library like node-fetch to make HTTP get requests in Node.js.

To make a HTTP GET request, use the following code. 

fetch(url)
 .then(res => {
    return res.json()
 })
 .then(data => {
   console.log(data)
 })
 .catch(error => {
   console.log(error)
 })

Alternatively, we could use the (cleaner) async-await version.

let url = 'https://api.nasa.gov/planetary/apod?api_key=DEMO_KEY'

 const getData = async () => {
    const res = await fetch(url)
    const data = await res.json()

    console.log(data)
}

getData()

 

Recap

HTTP get requests are used to fetch data from servers usually through APIs. In NodeJS, several methods that provide this functionality, starting with the http(s) module provided in the standard library. While the HTTP module works properly, making get requests is complicated.

You need to (locally) handle personal data and the code itself is verbose which can result in an error prone application. Libraries like Axios, SuperAgent, and Unirest were built to provide a simplistic and high level way of sending requests.

The article also mentions the introduction of the fetch API to NodeJS. With the API, you don't need to install any third party libraries but use it as you would on the client side.

 

Steve Alila

Steve Alila

He specializes in web design, WordPress development, and data analysis, with proficiency in Python, JavaScript, and data extraction tools. Additionally, he excels in web API development, AI integration, and data presentation using Matplotlib and Plotly. You can connect with him on his LinkedIn profile.

Can't find what you're searching for? Let us assist you.

Enter your query below, and we'll provide instant results tailored to your needs.

If my articles on GoLinuxCloud has helped you, kindly consider buying me a coffee as a token of appreciation.

Buy GoLinuxCloud a Coffee

For any other feedbacks or questions you can send mail to admin@golinuxcloud.com

Thank You for your support!!

3 thoughts on “How to make HTTP GET Request in Node.js [Practical Examples]”

Leave a Comment