How to make an HTTP request in Node.js like cURL?
I need to fetch data from a remote web service and return the response in a Node.js application. In PHP, I would have used cURL for this. What is the right way to achieve this in Node.js?
Additionally, how can I list all files in a directory using Node.js?
Node.js provides built-in modules like http and https for making HTTP requests, similar to how cURL works.
const https = require('https');
https.get('https://example.com', (res) => {
res.on('data', (data) => console.log(data.toString()));
});
If you’re looking for a higher-level solution similar to how you’d use cURL, the axios library is one of the most popular HTTP request libraries for Node.js.
npm install axios
const axios = require('axios');
axios.get('https://example.com/path/to/resource')
.then((response) => {
console.log(response.data);
})
.catch((error) => {
console.error('Error fetching data:', error);
});
Totally agree @Rashmihasija @richaaroy I believe these are the best solutions, but another great alternative to cURL in Node.js is the node-fetch library, which provides a fetch API similar to the one available in browsers.
npm install node-fetch
const fetch = require('node-fetch');
fetch('https://example.com/path/to/resource')
.then((response) => response.text())
.then((body) => {
console.log(body);
})
.catch((error) => {
console.error('Error fetching data:', error);
});
This API is clean and resembles the fetch function in the browser, making it a modern approach to HTTP requests in Node.js, similar to how you’d use cURL in PHP.