How to Use http.get in Node.js: Simple Guide with Example
In Node.js, you use
http.get to make simple HTTP GET requests by passing a URL and a callback to handle the response. The callback receives a response object where you can listen for data chunks and the end event to process the full response.Syntax
The http.get method takes a URL or options object and a callback function. The callback receives a response object to handle the incoming data stream.
- url: The URL string or options describing the request.
- callback: Function called with the response object.
You listen to data events to receive chunks and end event to know when the response is complete.
javascript
http.get(url[, options][, callback])Example
This example shows how to use http.get to fetch data from a website and print the full response body to the console.
javascript
import http from 'http'; const url = 'http://www.example.com'; http.get(url, (res) => { let data = ''; // Listen for data chunks res.on('data', (chunk) => { data += chunk; }); // When response ends, print the full data res.on('end', () => { console.log('Response received:'); console.log(data); }); }).on('error', (err) => { console.error('Error:', err.message); });
Output
Response received:
<!doctype html>\n<html>\n<head>\n <title>Example Domain</title>\n ... (rest of HTML content) ...
Common Pitfalls
Common mistakes when using http.get include:
- Not listening to the
dataevent, so the response body is never collected. - Not handling the
endevent, so you try to use incomplete data. - Ignoring errors by not attaching an
errorevent listener. - Using
http.getfor HTTPS URLs, which requires thehttpsmodule instead.
javascript
import http from 'http'; // Wrong: Not collecting data chunks http.get('http://www.example.com', (res) => { console.log('Status Code:', res.statusCode); // No data event listener here }); // Right: Collect data and handle errors http.get('http://www.example.com', (res) => { let data = ''; res.on('data', chunk => data += chunk); res.on('end', () => console.log(data)); }).on('error', err => console.error('Error:', err.message));
Quick Reference
- http.get(url, callback): Make a GET request to the URL.
- res.on('data', callback): Receive chunks of data.
- res.on('end', callback): Called when all data is received.
- req.on('error', callback): Handle request errors.
- Use
https.getfor HTTPS URLs.
Key Takeaways
Use
http.get with a callback to handle HTTP GET requests in Node.js.Always listen to
data and end events on the response to collect the full data.Attach an
error event listener to handle possible request errors.Use the
https module for HTTPS URLs instead of http.The response data comes in chunks, so accumulate them before using.