How to Make GET Request in Node.js: Simple Guide
In Node.js, you can make a GET request using the built-in
https or http modules by calling https.get() or http.get(). Alternatively, you can use popular libraries like axios or node-fetch for simpler syntax and promise-based handling.Syntax
To make a GET request in Node.js, you use the https.get() or http.get() method depending on the URL protocol. You pass the URL or options object and a callback function that handles the response.
- url: The web address you want to request.
- callback: A function that receives the response stream.
The response is a readable stream you can listen to for data chunks and the end event.
javascript
const https = require('https'); https.get('https://example.com', (res) => { // Handle response here });
Example
This example shows how to make a GET request to fetch data from a website using the built-in https module. It collects data chunks and prints the full response body.
javascript
const https = require('https'); https.get('https://jsonplaceholder.typicode.com/todos/1', (res) => { let data = ''; res.on('data', (chunk) => { data += chunk; }); res.on('end', () => { console.log('Response:', data); }); }).on('error', (err) => { console.error('Error:', err.message); });
Output
Response: {"userId":1,"id":1,"title":"delectus aut autem","completed":false}
Common Pitfalls
Common mistakes when making GET requests in Node.js include:
- Not handling errors with
on('error'), which can crash your app. - Forgetting to collect data chunks before processing the response.
- Using
httpmodule forhttpsURLs or vice versa.
Always check the URL protocol and handle errors properly.
javascript
const http = require('http'); // Wrong: Using http for https URL http.get('https://example.com', (res) => { // This will fail }); // Right: Use https module for https URLs const https = require('https'); https.get('https://example.com', (res) => { // Correct usage });
Quick Reference
Summary tips for making GET requests in Node.js:
- Use
https.get()for secure URLs andhttp.get()for non-secure URLs. - Always handle
errorevents to avoid crashes. - Collect data chunks before using the full response.
- Consider using libraries like
axiosornode-fetchfor simpler promise-based requests.
Key Takeaways
Use the built-in https or http module's get() method to make GET requests in Node.js.
Always handle errors with an error event listener to prevent your app from crashing.
Collect response data chunks before processing the full response body.
Match the module (http or https) to the URL protocol to avoid request failures.
For simpler code, consider using promise-based libraries like axios or node-fetch.