const request = require('request');
// Define the URL you want to make a request to
const url = 'https://api.example.com/data';
// Set up the options for the HTTP request
const options = {
method: 'GET', // Specify the HTTP method (GET, POST, etc.)
url: url, // Set the URL for the request
headers: {
'User-Agent': 'nodejs-request', // Set the user agent for the request
'Content-Type': 'application/json' // Set the content type for the request
}
};
// Make the HTTP request using the 'request' module
request(options, (error, response, body) => {
// Check for errors during the request
if (error) {
console.error('Error:', error);
return;
}
// Check if the response status code is successful (2xx)
if (response.statusCode >= 200 && response.statusCode < 300) {
// Parse the response body (assuming it's in JSON format)
const responseData = JSON.parse(body);
console.log('Response:', responseData);
} else {
// Handle non-successful response status codes
console.error('HTTP Status Code:', response.statusCode);
console.error('Response:', body);
}
});