How to make HTTP requests in Node.js without installing external libraries

Leo's dev blog

Houses near valley with trees

Published on
/3 mins read/---

When working with Node.js, there are many libraries that support creating requests to another server, such as node-fetch, phin, got or request (deprecated)...

However, if your server simply serves as an API for a client app and you now need to request a JSON file from another server or simply fetch an external API, which library should you choose to use?

The answer is that you don't need to add a new dependency to your package.json just for creating a request because Node.js has a built-in module called https.

HTTPS

https is a lightweight module that comes pre-built in Node.js and is supported in most Node.js versions.

You can create a request using https as follows:

In the code above:

  • https is a built-in module in Node.js so you can require it directly without the need for installation.
  • You can create a request using https.get(url[, options][, callback]).
  • In the callback, you listen to the response events using res.on().
  • Each time res.on("data") is triggered, you add the data to the string body.
  • When res.on("end") is triggered, you can simply parse the body into a JSON object using JSON.parse(body).
  • Lines 8 and 11: Note that you should parse the data within a try {} catch() {} block to catch errors if the JSON cannot be parsed.
  • If the request fails, the error event will be triggered.

That's it! Now let's abstract this logic into a function that can be used anywhere in the server:

And you can use it as follows:

Good luck!