跳到主要內容

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

留言

這個網誌中的熱門文章

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

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智能眼罩 觸...
自製直播音源線 Bird Liang   October 6, 2016   in  View Bird Liang, Chief Engineer (梁子凌 / 技術長兼工程輔導長) 負責 AppWorks 技術策略與佈署,同時主導工程輔導。人生的第一份正職工作是創業,之後在外商圈電子業中闖蕩多年,經歷過 NXP、Sony、Newport Imagining、Crossmatch 等企業,從事無線通訊、影像系統、手機、面板、半導體、生物辨識等不同領域產品開發。熱愛學習新事物,協助團隊解決技術問題。放棄了幾近退休般的生活加入 AppWorks,為的是幫助更多在創業路上的人,並重新體驗創業的熱情。台大農機系、台科大電子所畢業,熱愛賞鳥、演奏管風琴,亦是不折不扣的熱血 Maker。 隨著 Facebook 開放一般帳號直播,現在我們只要拿起手機,隨時隨地都可以開始直播。回想幾年前 AppWorks 剛開始進行 Demo Day 直播時,還要將 HDMI 訊號接進 PC 中、再編碼打進 YouTube 的複雜度,實不可同日而語。 但用手機或平板直播最大的問題往往不是影像而是聲音。iPhone 或 iPad 上的攝影機,感度和解析度早已不輸數年前的專業攝影機,只要現場光不太差,大概都可以拍出令人滿意的畫面。但直播的聲音一直是個大問題,手機上的麥克風跟人耳所聽到的聲音其實有很大的差距,在比較大的場子裡,光是仰賴內建麥克風的收音多半無法有令人滿意的效果。 在大型的活動中,現場通常會有 PA 系統,最理想的方式還是想辦法將 PA 的訊號餵進 iPad 或 iPhone 中,保證聲音乾淨又清楚,絕對不會有其它有的沒的現場音。 iPhone 的耳機孔雖然可以插帶有麥克風的耳機 (如 Apple 原廠的 EarPods),但它的訊號位準是電容式麥克風的位準。PA 控台的輸出幾乎都是 line level 的,兩者的訊號電壓相差百倍以上,我們得做個小東西來解決這個差距。 Line 與 Mic 在 mixer 上,我們常會看到輸入可以在兩種規格中切換: line level 和 mic level。Mic level 顧名思義就是從麥克風來的訊號,這個訊號的規格是從不需供電的傳統動圈麥克風來的。因為不需...