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:
We import the
axioslibrary, which provides a simple way to make HTTP requests.We define an asynchronous
mainfunction 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’. Theawaitkeyword 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:
$ npm init -y
$ npm install axios typescript ts-node @types/node- Save the code in a file named
http-client.ts. - Run the code using ts-node:
$ npx ts-node http-client.tsThis 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.