Making HTTP Calls in Node.js Using Built-in HTTP Module

Node.js provides powerful built-in modules for handling network operations, including the HTTP module. This article will explore how to make various HTTP calls using Node.js’s native HTTP module, focusing on GET, POST, PUT, and DELETE requests. We’ll also discuss best practices and provide detailed examples to help you master HTTP calls in Node.js.

Introduction to Node.js HTTP Module

The HTTP module is a core part of Node.js, designed for creating server-side applications and making HTTP requests. It’s lightweight, efficient, and doesn’t require any external dependencies.

To use the HTTP module, you first need to require it in your Node.js application:

const http = require('http');

GET Request

GET requests are used to retrieve data from a server. Here’s how to make a GET request using the Node.js HTTP module:

const http = require('http');

const options = {
  hostname: 'api.example.com',
  port: 80,
  path: '/data',
  method: 'GET'
};

const req = http.request(options, (res) => {
  let data = '';

  res.on('data', (chunk) => {
    data += chunk;
  });

  res.on('end', () => {
    console.log(JSON.parse(data));
  });
});

req.on('error', (error) => {
  console.error(`Problem with request: ${error.message}`);
});

req.end();

This example sends a GET request to ‘api.example.com/data’ and logs the response data.

POST Request

POST requests are used to send data to a server to create or update a resource. Here’s an example of a POST request:

const http = require('http');

const data = JSON.stringify({
  name: 'John Doe',
  job: 'Developer'
});

const options = {
  hostname: 'api.example.com',
  port: 80,
  path: '/users',
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    'Content-Length': data.length
  }
};

const req = http.request(options, (res) => {
  let responseData = '';

  res.on('data', (chunk) => {
    responseData += chunk;
  });

  res.on('end', () => {
    console.log(JSON.parse(responseData));
  });
});

req.on('error', (error) => {
  console.error(`Problem with request: ${error.message}`);
});

req.write(data);
req.end();

This example sends a POST request with JSON data to create a new user.

PUT Request

PUT requests are used to update existing resources on the server. Here’s how to make a PUT request:

const http = require('http');

const data = JSON.stringify({
  name: 'John Doe',
  job: 'Senior Developer'
});

const options = {
  hostname: 'api.example.com',
  port: 80,
  path: '/users/123',
  method: 'PUT',
  headers: {
    'Content-Type': 'application/json',
    'Content-Length': data.length
  }
};

const req = http.request(options, (res) => {
  let responseData = '';

  res.on('data', (chunk) => {
    responseData += chunk;
  });

  res.on('end', () => {
    console.log(JSON.parse(responseData));
  });
});

req.on('error', (error) => {
  console.error(`Problem with request: ${error.message}`);
});

req.write(data);
req.end();

This example updates the user with ID 123 using a PUT request.

DELETE Request

DELETE requests are used to remove resources from the server. Here’s an example of a DELETE request:

const http = require('http');

const options = {
  hostname: 'api.example.com',
  port: 80,
  path: '/users/123',
  method: 'DELETE'
};

const req = http.request(options, (res) => {
  console.log(`Status Code: ${res.statusCode}`);

  res.on('data', (chunk) => {
    console.log(`Response Body: ${chunk}`);
  });
});

req.on('error', (error) => {
  console.error(`Problem with request: ${error.message}`);
});

req.end();

This example sends a DELETE request to remove the user with ID 123.

Best Practices for HTTP Calls in Node.js

  1. Error Handling: Always include error handling in your HTTP requests to manage network issues or server errors.
  2. HTTPS: For secure communications, use the https module instead of http.
  3. Timeouts: Set request timeouts to prevent your application from hanging indefinitely.
  4. Streaming: For large payloads, use streams to efficiently handle data.
  5. Proper Headers: Set appropriate headers for your requests, such as ‘Content-Type’ for POST and PUT requests.

Conclusion

The Node.js HTTP module provides a powerful and flexible way to make HTTP calls without relying on external libraries. By understanding how to use this built-in module for GET, POST, PUT, and DELETE requests, you can efficiently communicate with web services and APIs in your Node.js applications.

Remember to handle errors, use HTTPS for secure communications, and follow best practices to ensure your HTTP calls are robust and efficient. With these tools and knowledge, you’re well-equipped to build scalable and performant network applications in Node.js.

Shahid
Shahid

Founder of Codeforgeek. Technologist. Published Author. Engineer. Content Creator. Teaching Everything I learn!

Articles: 128