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 requestres: 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 usinghttp.request(), which causes the request to never send. - Ignoring errors by not adding an
errorevent listener on the request. - Assuming the response data comes all at once instead of listening for
dataevents 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:
| Method | Use Case |
|---|---|
| GET | Retrieve data from a server |
| POST | Send data to a server to create something |
| PUT | Update existing data on a server |
| DELETE | Remove data from a server |
| HEAD | Get 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.