跳到主要內容

4 + 1 ways for making HTTP requests with Node.js: async/await edition

HTTP requests with Node.js are a means for fetching data from a remote source. It could be an API, a website, or something else: at one point you will need some code to get meaningful data from one of those remote sources.
4 + 1 ways for making HTTP requests with Node.js: async/await edition
During your career as a Web Developer you will work with HTTP requests all the time. This is why in the following post I want to introduce you to some different ways for making HTTP requests in Node.js.
Starting from the easier one we will explore the “classic way” for doing HTTP requests all the way through libraries which support Promises.
I will focus mostly on GET requests in order to keep things simple and understandable.

What you will learn

  1. How to make HTTP requests in Node.js with various modules
  2. The prons and cons of every module

Requirements

To follow along you should have a basic understanding of Javascript and ES6.
Also, make sure to have one of the latest versions of Node. In the following post I’ll make use of the async/await pattern, introduced into Node 7.6.0.

Making HTTP requests with Node.js: why?

At this point you might be asking yourself “Why would I ever do a HTTP request?”.
The answer is simple: as a Javascript developer you will interact every day with remote APIs and webservers. Almost everything today is available in the form of an API: weather forecasts, geolocation services and so on.
Node.js can be used to serve a vaste range of purposes: you can build a command line tool, a proxy, a webserver, and in its simplest form it can be used just for querying a remote API and returning the output to the user.
In the next examples we’ll be making HTTP requests with Node.js by querying the Google Maps API  a convenient “fake” API: the JSON Placeholder API.
(Google Maps API does not accept unauthenticated requests anymore).

Making HTTP requests with Node.js: old school HTTP requests with callbacks

To start, create an empty directory named making-http-requests-node-jsand run:
  1. npm init -y
to initialize package.json. The -y flag configures package.json with the default values rather than asking us any questions.
There are two simple ways for making HTTP requests with Node.js as of today: by using a library which follows the classic callback pattern or even better by using a library which supports Promises.
Working with Promises means you could also use the async/await keywords.
Let’s start with callbacks!

Making HTTP requests with Node.js: http.get and https.get

Making HTTP requests with Node.js: http.get and https.get
The documentation for http.get
http.get or https.get (for HTTPS requests), are the first choices for making requests in Node.js. If you just need to GET something from an API, stick with them.
PROS:
  1. native API, there is no need to install third party modules
  2. the response is a stream*
CONS:
  1. a bit verbose
  2. the response is a stream*
  3. no support for promises
To test things out create a new file named https-native.js:
  1. const https = require("https");
  2. const url = "https://jsonplaceholder.typicode.com/posts/1";
  3. https.get(url, res => {
  4. res.setEncoding("utf8");
  5. let body = "";
  6. res.on("data", data => {
  7. body += data;
  8. });
  9. res.on("end", () => {
  10. body = JSON.parse(body);
  11. console.log(body);
  12. });
  13. });
Now if you run this code with:
  1. node https-native.js
you should be able to see the following output:
  1. { userId: 1,
  2. id: 1,
  3. title:
  4. 'sunt aut facere repellat provident occaecati excepturi optio reprehenderit',
  5. body:
  6. 'quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerumest autem sunt rem eveniet architecto' }
https.get expects an url as a first argument and a callback as a second argument. The returned response is an http.ClientRequest object. That means, in order to manipulate the body of the response you have to listen for events: notice the res.on() in the above example.
Now, in this example I’m just logging the response to the console. In a real program you may want to pass the response to a callback.
*The http.ClientRequest object emits some events that you can listen to. And that’s both good and “bad”: good because you will be tempted to dig further into the Node.js internals to learn more and “bad” because you are forced to do a lot of manipulation if you want to extract the JSON response.
In the end, working with http.get could be slightly more verbose compared to other libraries but that shouldn’t be necessarily considered a drawback because in the process you will learn more about Node.js internals.

Making HTTP requests with Node.js: the request module

Making HTTP requests with Node.js: the request module
The request NPM module
request is one of the most popular NPM module for making HTTP requests with Node.js. It supports both HTTP and HTTPS and follows redirects by default.
PROS:
  1. ease of use
CONS:
  1. no support for promises
  2. too many dependencies
To install the module run:
  1. npm i request
inside your project folder.
To test out the example create a new file named request-module.js:
  1. const request = require("request");
  2. const url = "https://jsonplaceholder.typicode.com/posts/1";
  3. request.get(url, (error, response, body) => {
  4. let json = JSON.parse(body);
  5. console.log(body);
  6. });
By running the code with:
  1. node request-module.js
you should be able to see the same output as in the previous example.
request.get expects an url as a first argument and a callback as a second argument.
Working with the request module is pleasing. As you can see in the example, it is much more concise than http.get.
There’s a drawback though: request carries 22 dependencies. Now, I wouldn’t consider this a real problem but if your goal is to make just an HTTP GET request, sticking with http.get will be enough to get the job done.
The request module does not support promises. It could be promisified with util.promisify or even better you could use request-promise, a request version which returns promises (and has less dependencies).

Making HTTP requests with Node.js: I Promise I’ll be async

So far we’ve seen how to make HTTP requests in the most basic way with callbacks.
But there is a better (sometimes) way to handle async code: by using Promises alongside with the new async/await keywords.
In the next examples we’ll see how to use a bunch of Node.js modules which support Promises out of the box.

Making HTTP requests with Node.js: the node-fetch module

Making HTTP requests with Node.js: the node-fetch module
The node-fetch module
node-fetch is an implementation of the native Fetch API for Node.js. It’s basically the same as window.fetch so if you’re accustomed to use the original it won’t be difficult to pick the Node.js implementation.
PROS:
  1. support for promises
  2. same API as window.fetch
  3. few dependencies
CONS:
  1. same API as window.fetch
To install the module run:
  1. npm i node-fetch
To test out the example create a new file named node-fetch.js:
  1. const fetch = require("node-fetch");
  2. const url = "https://jsonplaceholder.typicode.com/posts/1";
  3. const getData = async url => {
  4. try {
  5. const response = await fetch(url);
  6. const json = await response.json();
  7. console.log(json);
  8. } catch (error) {
  9. console.log(error);
  10. }
  11. };
  12. getData(url);
By running the code with:
  1. node node-fetch.js
you should be able to see the same output again.
If you paid attention I’ve listed “same API as window.fetch” both in Pros and Cons.
That’s because not everybody likes the Fetch API. Some people can’t stand out the fact that in order to manipulate the response you have to call json() (and some other quirks).
But in the end it’s a matter of getting the job done: use whichever library you prefer.

Making HTTP requests with Node.js: the r2 module

The request module for Node.js was written by Mikeal Rogers back in 2010. In 2017 he is back with the r2 module.
The r2 module uses Promises and is another implementation of the browser’s Fetch API. That means r2 depends on node-fetch.
At first it wasn’t clear to me why would I consider using r2 over node-fetch. But I thought the module is worth a mention.
PROS:
  1. support for promises
  2. same API as window.fetch
  3. few dependencies
CONS:
  1. it depends on node-fetch
To install the module run:
  1. npm i r2
To test things out create a new file named r2-module.js:
  1. const r2 = require("r2");
  2. const url = "https://jsonplaceholder.typicode.com/posts/1";
  3. const getData = async url => {
  4. try {
  5. const response = await r2(url).json;
  6. console.log(response);
  7. } catch (error) {
  8. console.log(error);
  9. }
  10. };
  11. getData(url);
Run the code with:
  1. node r2-module.js
and you should be able to see (again).
By comparing r2 to node-fetch I can see it is less verbose. I saved 1 line of code.
In all honesty I didn’t take the time to look at r2 in details. Maybe because it is almost the same as node-fetch. But I’m sure it has more to offer.

Making HTTP requests with Node.js: the axios module

Making HTTP requests with Node.js: the axios module
The axios NPM module
Axios is another super popular NPM module for making HTTP requests. It supports Promises by default.
Axios can be used both for the front-end and the back-end and one of its core feature is the ability to transform both the request and the response.
Plus you don’t need to explicitly process the response in order to get the JSON as you did with node-fetch: axios will do it automagically.
PROS:
  1. support for promises
  2. ease of use
  3. 2 dependencies
CONS:
  1. ??
Run:
  1. npm i axios
to install axios inside your project folder.
To test out the example create a new file named axios-module.js:
  1. const axios = require("axios");
  2. const url = "https://jsonplaceholder.typicode.com/posts/1";
  3. const getData = async url => {
  4. try {
  5. const response = await axios.get(url);
  6. const data = response.data;
  7. console.log(data);
  8. } catch (error) {
  9. console.log(error);
  10. }
  11. };
  12. getData(url);
Again, by running the above code you should be able to see the same output of the previous examples.
I really can’t find any drawback in axios. It’s super simple to use, highly configurable and intuitive. Last but not least it has only 2 dependencies.

Making HTTP requests with Node.js: in conclusion

All the above libraries share one common denominator: each of them produces the same result. As with almost everything with Javascript sometimes picking one module over another it’s a matter of personal preferences.
In the end, I feel that by using the native API methods you can learn more about the Node.js internals, and that’s both great and educational.
My rule of thumb is to pick the smallest library with the fewer dependencies possible based on what I want to do.
If I were to make a super simple GET request I wouldn’t install neither axios nor node-fetch.
In contrast, using a third party module could save you a lot of coding when in need for more complex functions: i.e. request and response manipulation.

A small note about “Making HTTP requests with Node.js”

A lot has changed since the first version of this blog post. I’ve received a lot of useful comments plus some recommendations.
In the meantime async/await became a thing so I thought it would be nice to update the article with modern examples. Plus, since I care about my own blog, better to bring the article back where it belongs: here.
Thanks for reading!

But! … I want more!

Looking for more articles about Node.js? Fear not, I’ve got you covered: take a look at How to inspect the memory usage of a process in Node.Js and Going real time with Socket.IO, Node.Js and React

留言

這個網誌中的熱門文章

2017通訊大賽「聯發科技物聯網開發競賽」決賽團隊29強出爐!作品都在11月24日頒獎典禮進行展示

2017通訊大賽「聯發科技物聯網開發競賽」決賽團隊29強出爐!作品都在11月24日頒獎典禮進行展示 LIS   發表於 2017年11月16日 10:31   收藏此文 2017通訊大賽「聯發科技物聯網開發競賽」決賽於11月4日在台北文創大樓舉行,共有29個隊伍進入決賽,角逐最後的大獎,並於11月24日進行頒獎,現場會有全部進入決賽團隊的展示攤位,總計約為100個,各種創意作品琳琅滿目,非常值得一看,這次錯過就要等一年。 「聯發科技物聯網開發競賽」決賽持續一整天,每個團隊都有15分鐘面對評審團做簡報與展示,並接受評審們的詢問。在所有團隊完成簡報與展示後,主辦單位便統計所有評審的分數,並由評審們進行審慎的討論,決定冠亞季軍及其他各獎項得主,結果將於11月24日的「2017通訊大賽頒獎典禮暨成果展」現場公佈並頒獎。 在「2017通訊大賽頒獎典禮暨成果展」現場,所有入圍決賽的團隊會設置攤位,總計約為100個,展示他們辛苦研發並實作的作品,無論是想觀摩別人的成品、了解物聯網應用有那些新的創意、尋找投資標的、尋找人才、尋求合作機會或是單純有興趣,都很適合花點時間到現場看看。 頒獎典禮暨成果展資訊如下: 日期:2017年11月24日(星期五) 地點:中油大樓國光廳(台北市信義區松仁路3號) 我要報名參加「2017通訊大賽頒獎典禮暨成果展」>>> 在參加「2017通訊大賽頒獎典禮暨成果展」之前,可以先在本文觀看各團隊的作品介紹。 決賽29強團隊如下: 長者安全救星 可隨意描繪或書寫之電子筆記系統 微觀天下 體適能訓練管理裝置 肌少症之行走速率檢測系統 Sugar Robot 賽亞人的飛機維修輔助器 iTemp你的溫度個人化管家 語音行動冰箱 MR模擬飛行 智慧防盜自行車 跨平台X-Y視覺馬達控制 Ironmet 菸消雲散 無人小艇 (Mini-USV) 救OK-緊急救援小幫手 穿戴式長照輔助系統 應用於教育之模組機器人教具 這味兒很台味 Aquarium Hub 發展遲緩兒童之擴增實境學習系統 蚊房四寶 車輛相控陣列聲納環境偵測系統 戶外團隊運動管理裝置 懷舊治療數位桌曆 SeeM智能眼罩 觸...
opencv4nodejs Asynchronous OpenCV 3.x Binding for node.js   122     2715     414   0   0 Author Contributors Repository https://github.com/justadudewhohacks/opencv4nodejs Wiki Page https://github.com/justadudewhohacks/opencv4nodejs/wiki Last Commit Mar. 8, 2019 Created Aug. 20, 2017 opencv4nodejs           By its nature, JavaScript lacks the performance to implement Computer Vision tasks efficiently. Therefore this package brings the performance of the native OpenCV library to your Node.js application. This project targets OpenCV 3 and provides an asynchronous as well as an synchronous API. The ultimate goal of this project is to provide a comprehensive collection of Node.js bindings to the API of OpenCV and the OpenCV-contrib modules. An overview of available bindings can be found in the  API Documentation . Furthermore, contribution is highly appreciated....
2019全台精選3+個燈會,週邊順遊景點懶人包 2019燈會要去哪裡看?全台精選3+個燈會介紹、週邊順遊景點整理給你。 東港小鎮燈區-鮪鮪到來。 2019-02-15 微笑台灣編輯室 全台灣 各縣市政府 1435 延伸閱讀 ►  元宵節不只看燈會!全台元宵祭典精選、順遊景點整理 [屏東]2019台灣燈會在屏東 2/9-3/3:屏東市 · 東港鎮 · 大鵬灣國家風景區 台灣燈會自1990年起開始辦理,至2019年邁入第30週年,也是首次在屏東舉辦,屏東縣政府與交通部觀光局導入創新、科技元素,融入在地特色文化設計,在東港大鵬灣國家風景區打造廣闊的海洋灣域燈區,東港鎮結合漁港及宗教文化的小鎮燈區,及屏東市綿延近5公里長的綵燈節河岸燈區,讓屏東成為璀璨的光之南國,迎向國際。 詳細介紹 ►  2019台灣燈會在屏東 第一次移師國境之南 大鵬灣燈區 主題樂園式燈會也是主燈所在區,區內分為農業海洋燈區、客家燈區、原住民燈區、綠能環保燈區、藝術燈區、宗教燈區、競賽花燈及317個社區關懷據點手作的萬歲光廊等。 客家燈籠隧道。 平日:周一~周四14:00-22:30(熄燈) 假日:周五~周六10:00-22:30(熄燈)  屏東燈區: 萬年溪畔 屏東綵燈節藍區-生態。 綵燈節--每日17:30 - 22:00(熄燈) 勝利星村--平日:14:00 - 22:30(熄燈) 假日:10:00 - 22:30(熄燈) 燈區以「彩虹」為主題,沿著蜿蜒市區的萬年溪打造近5公里長的光之流域,50組水上、音樂及互動科技等不同類型燈飾,呈現紅色熱情、橙色活力、黃色甜美、綠色雄偉、藍色壯闊、靛色神祕、紫色華麗等屏東風情。勝利星村另有懷舊風的燈飾,及屏東公園聖誕節燈飾。 東港小鎮燈區 東港小鎮燈區-鮪鮪到來。 小鎮燈區以海的屏東為主題,用漁港風情及宗教文化內涵規劃4個主題區,分別為張燈結綵趣、東津好風情、神遊幸福海、延平老街區。每日17:00~22:30(熄燈) 以上台灣燈會資料來源: 2019台灣燈會官網 、 i屏東~愛屏東 。 >> 順遊行程 小吃旅行-東港小鎮 東港小吃和東港人一樣,熱情澎湃...