In this article, we explore two methods for retrieving the JSON data from a URL in Node.js.Using the built-in https module and the axios library. The https module requires manual data handling , where as axios simplifies that task by automatic error management and parsing.
Getting JSON data involves sending a request to a specific URL and receiving structured data in JSON format, this is commonly used in APIs for exchanging information between applications
we can use these methods:
- Using https module
- Using axios library
Using https Module
Node.js has a built in module https that we can use to fetch data from a URL. When you request data , it sends the data in chunks which we can also call it as small parts of data. We need to collect these chunks, combine them, and finally process for the final result
Example:
const https = require('https'); const url = 'https://jsonplaceholder.typicode.com/posts/1'; https.get(url, (res) => { let data = ''; // Collect data chunks res.on('data', (chunk) => { data += chunk; }); // Parse and display data res.on('end', () => { const jsonData = JSON.parse(data); console.log('Fetched Data:', jsonData); }); }).on('error', (err) => { console.error('Error:', err.message); });
Output:
Fetched Data: { id: 1, title: '...', body: '...', userId: 1 }
In this example the method used uses event listeners to handle the incoming data chunks, and once all the chunks are received then the data is parsed into JSON format
Using axios Library
The axios library is simplified version of the https method in this it handles everything it self including error management and JSON parsing . It simplifies HTTP requests by providing a clean and Promising API. It makes fetching JSON data more readable and easier to handle than the https module.
Install axios library using this script command:
npm install axios
Example:
const axios = require('axios'); const url = 'https://jsonplaceholder.typicode.com/posts/1'; axios.get(url) .then((response) => { console.log('Fetched Data:', response.data); }) .catch((error) => { console.error('Error:', error.message); });
Output:
Fetched Data: { id: 1, title: '...', body: '...', userId: 1 }
This approach is easier and handles both data retrieval and errors more effectively.