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:

import axios from 'axios';

async function main() {
  try {
    // Make an HTTP GET request to a server
    const response = await axios.get('https://example.com');

    // Print the HTTP response status
    console.log('Response status:', response.status);

    // Print the first 5 lines of the response body
    const lines = response.data.split('\n');
    for (let i = 0; i < 5 && i < lines.length; i++) {
      console.log(lines[i]);
    }
  } catch (error) {
    if (axios.isAxiosError(error)) {
      console.error('Error making request:', error.message);
    } else {
      console.error('Unexpected error:', error);
    }
  }
}

main();

This TypeScript example demonstrates how to make an HTTP GET request using the popular axios library. Here’s a breakdown of the code:

  1. We import the axios library, which provides a simple way to make HTTP requests.

  2. We define an asynchronous main function to handle the HTTP request and response.

  3. Inside a try-catch block, we use axios.get() to make a GET request to ‘https://example.com’. The await keyword is used to wait for the response.

  4. We print the HTTP response status using console.log().

  5. 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.

  6. 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:

  1. Make sure you have Node.js and npm installed.
  2. Install the necessary dependencies:
$ npm init -y
$ npm install axios typescript ts-node @types/node
  1. Save the code in a file named http-client.ts.
  2. Run the code using ts-node:
$ npx ts-node http-client.ts

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.