Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Making HTTP requests using Typescript or NodeJS

I'm looking for a definitive way to handle simple HTTP requests to a REST API using modern javascript frameworks, in my case Typescript but I guess it would also apply to Nodejs.

Since there doesn't seem to be a simple native way to do this, I have found a plethora of libraries, some now deprecated and dozen's of articles dating back several years some with updates based on the newer best practises. Surely it can't be that hard. This takes me about 5mins to implement in Golang or Python, but alas with JavaScript its a pain - Is it just me?

Could somebody please clarify the current state of play and recommended way to do this based on where we are now in 2020.

like image 543
user1513388 Avatar asked Jun 28 '26 04:06

user1513388


1 Answers

Even though request-promise-native probably works just fine, Axios is a way better alternative for use in TypeScript. It comes with its own type definitions and is overall less dependent on other packages. Using it's API is quite like the answer provided by Adrian, however there are a few subtle differences.

const url: string = 'your-url.example';

try {
    const response = await axios.get(yourUrl);
} catch (exception) {
    process.stderr.write(`ERROR received from ${url}: ${exception}\n`);
}
like image 137
Athish Murugan Avatar answered Jun 29 '26 18:06

Athish Murugan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!