Http Client in TypeScript
Here’s an idiomatic TypeScript example demonstrating how to make an HTTP GET request, similar to the concept shown in the Go example:
This TypeScript example demonstrates how to make an HTTP GET request using the popular axios
library. Here’s a breakdown of the code:
We import the
axios
library, which provides a simple way to make HTTP requests.We define an asynchronous
main
function to handle the HTTP request and response.Inside a try-catch block, we use
axios.get()
to make a GET request to ‘https://example.com’. Theawait
keyword is used to wait for the response.We print the HTTP response status using
console.log()
.To print the first 5 lines of the response body, we split the response data into an array of lines and use a for loop to iterate through them.
Error handling is done in the catch block. We use
axios.isAxiosError()
to check if it’s an Axios-specific error, providing more detailed error information.
To run this TypeScript code:
- Make sure you have Node.js and npm installed.
- Install the necessary dependencies:
- Save the code in a file named
http-client.ts
. - Run the code using ts-node:
This example showcases TypeScript’s async/await syntax for handling promises, type-safe error handling, and the use of third-party libraries like axios for making HTTP requests. It’s a more modern and type-safe approach compared to using the built-in http
module in Node.js.