跳到主要內容

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

完形心理學!?讓我們了解“介面設計師”為什麼這樣設計

完形心理學!?讓我們了解“介面設計師”為什麼這樣設計 — 說服客戶與老闆、跟工程師溝通、強化設計概念的有感心理學 — 情況 1 : 為何要留那麼多空白? 害我還要滾動滑鼠(掀桌) 情況 2 : 為什麼不能直接用一頁展現? 把客戶的需求塞滿不就完工啦! (無言) 情況 3: 這種設計好像不錯,但是為什麼要這樣做? (直覺大神告訴我這樣設計,但我說不出來為什麼..) 雖然世界上有許多 GUI 已經走得又長又遠又厲害,但別以為這種古代人對話不會出現,一直以來我們只是習慣這些 GUI 被如此呈現,但為何要這樣設計我們卻不一定知道。 由於 完形心理學 歸納出人類大腦認知之普遍性的規則,因此無論是不是 UI/UX 設計師都很適合閱讀本篇文章。但還是想特別強調,若任職於傳統科技公司,需要對上說服老闆,需要平行說服(資深)工程師,那請把它收進最愛;而習慣套用設計好的 UI 套件,但不知道為何這樣設計的 IT 工程師,也可以透過本文來強化自己的產品說服力。 那就開始吧~(擊掌) 完形心理學,又稱作格式塔(Gestalt)心理學,於二十世紀初由德國心理學家提出 — 用以說明人類大腦如何解釋肉眼所觀察到的事物,並轉化為我們所認知的物件。它可說是現代認知心理學的基礎,其貫徹的概念就是「整體大於個體的總合 “The whole is other than the sum of the parts.” —  Kurt Koffka」。 若深究完整的理論將會使本文變得非常的艱澀,因此筆者直接抽取個人認為與 UI 設計較為相關的 7 個原則(如下),並搭配實際案例做說明。有興趣了解全部理論的話可以另外 Google。 1. 相似性 (Similarity)  — 我們的大腦會把相似的事物看成一體 如果數個元素具有類似的尺寸、體積、顏色,使用者會自動為它們建立起關聯。這是因為我們的眼睛和大腦較容易將相似的事物組織在一起。如下圖所示,當一連串方塊和一連串的圓形並排時,我們會看成(a)一列方塊和兩列圓形(b)一排圓形和兩排三角形。 對應用到介面設計上,FB 每則文章下方的按鈕圖標(按讚 Like / 留言Comment / 分享 Share)雖然功能各不相同,但由於它們在視覺上顏色、大小、排列上的相似性,用戶會將它們視認為...