0
0
NodejsHow-ToBeginner · 4 min read

How to Make HTTP Request in Node.js: Simple Guide

In Node.js, you can make HTTP requests using the built-in http or https modules for basic needs, or use popular libraries like node-fetch or axios for easier and more powerful requests. These tools let you send GET, POST, and other requests to servers and handle responses asynchronously.
📐

Syntax

Node.js provides the http and https modules to make HTTP requests. You create a request by calling http.request() or https.request() with options like URL, method, and headers. Then you listen for response events to get data.

Key parts:

  • options: Object with request details (hostname, path, method, headers)
  • req: The request object to send data or end the request
  • res: The response object to read data from the server
javascript
const http = require('http');

const options = {
  hostname: 'example.com',
  path: '/',
  method: 'GET',
  headers: {
    'Content-Type': 'application/json'
  }
};

const req = http.request(options, (res) => {
  let data = '';
  res.on('data', (chunk) => {
    data += chunk;
  });
  res.on('end', () => {
    console.log('Response:', data);
  });
});

req.on('error', (error) => {
  console.error('Error:', error);
});

req.end();
💻

Example

This example shows how to make a simple GET request to https://jsonplaceholder.typicode.com/todos/1 using the node-fetch library, which is easier than the built-in modules. It fetches JSON data and prints the title.

javascript
import fetch from 'node-fetch';

async function getTodo() {
  try {
    const response = await fetch('https://jsonplaceholder.typicode.com/todos/1');
    if (!response.ok) {
      throw new Error('Network response was not ok');
    }
    const todo = await response.json();
    console.log('Todo title:', todo.title);
  } catch (error) {
    console.error('Fetch error:', error);
  }
}

getTodo();
Output
Todo title: delectus aut autem
⚠️

Common Pitfalls

Common mistakes when making HTTP requests in Node.js include:

  • Not calling req.end() when using http.request(), which causes the request to never send.
  • Ignoring errors by not adding an error event listener on the request.
  • Assuming the response data comes all at once instead of listening for data events and concatenating chunks.
  • Not handling non-200 HTTP status codes properly.
javascript
const http = require('http');

// Wrong: missing req.end(), request never sent
const reqWrong = http.request('http://example.com', (res) => {
  console.log('This will never run');
});

// Right: call req.end() to send request
const reqRight = http.request('http://example.com', (res) => {
  res.on('data', (chunk) => {
    console.log('Data chunk:', chunk.toString());
  });
});
reqRight.end();
📊

Quick Reference

Here is a quick summary of HTTP request methods and their common uses:

MethodUse Case
GETRetrieve data from a server
POSTSend data to a server to create something
PUTUpdate existing data on a server
DELETERemove data from a server
HEADGet headers only, no body

Key Takeaways

Use built-in http or https modules for basic HTTP requests in Node.js.
Call req.end() to actually send the request when using http.request().
Consider using libraries like node-fetch or axios for simpler and more readable code.
Always handle errors and response status codes to avoid silent failures.
Listen to data events to collect response chunks before processing.