Http Client in JavaScript
Here’s an idiomatic JavaScript example that demonstrates the concept of making an HTTP request, similar to the Go example provided:
// Import the 'node-fetch' package for making HTTP requests
// Note: For Node.js versions 18 and above, you can use the built-in fetch API
import fetch from 'node-fetch';
async function main() {
try {
// Make an HTTP GET request to a server
const response = await fetch('https://api.example.com');
// Print the HTTP response status
console.log('Response status:', response.status, response.statusText);
// Get the response body as text
const body = await response.text();
// Print the first 5 lines of the response body
const lines = body.split('\n');
console.log('First 5 lines of the response body:');
for (let i = 0; i < 5 && i < lines.length; i++) {
console.log(lines[i]);
}
} catch (error) {
console.error('An error occurred:', error);
}
}
main();This JavaScript example demonstrates how to make an HTTP GET request using the fetch function, which is similar to the http.Get function in Go. Here’s a breakdown of the code:
We import the
node-fetchpackage, which provides afetchfunction similar to the one available in browsers. For Node.js versions 18 and above, you can use the built-infetchAPI without importing an external package.We define an asynchronous
mainfunction to handle the HTTP request and response.Inside a try-catch block, we use
await fetch()to make an HTTP GET request to a server. This is equivalent tohttp.Get()in the Go example.We print the HTTP response status using
console.log(), which is similar tofmt.Println()in Go.We retrieve the response body as text using
await response.text().We split the response body into lines and print the first 5 lines using a for loop, similar to the Go example.
If any errors occur during the process, they are caught in the catch block and logged to the console.
Finally, we call the
main()function to execute our code.
To run this example:
- Save the code in a file named
http-client.js. - Make sure you have Node.js installed on your system.
- Install the
node-fetchpackage by runningnpm install node-fetchin your terminal. - Run the script using Node.js:
$ node http-client.jsThis example demonstrates how to make HTTP requests in JavaScript, handle responses, and process the response data. It follows JavaScript best practices by using async/await for handling asynchronous operations and try-catch for error handling.