

However, the readability is top-notch, and configuring other http requests are just as simple as this Get request example! Per the benchmark results above, this is the slowest option, most likely because so much is happening under-the-hood. This readability comes at the price of speed, however. So, to access the JSON we want, just use the body variable!
Nodejs request code#
get ( url ,( res ) =>, we tell the request to automatically parse the response's body as JSON if there's no error (and we get a 200 status code back).
Nodejs request install#
To install, run npm install node-fetch, and set up your code like this:Ĭonst https = require ( ' https ' ) let url = " " https. The node-fetch package does pretty much what you expect: provide you with the fetch() syntax in Node.js. Replicating fetch() with 'node-fetch' package Having this handy will make parsing and accessing the data you need way faster and easier. On top of that, hovering your cursor over a particular field will show the path to access it:Ĭursor hovering over the "ups" field, with the path shown in the bottom-left corner Same JSON from, pretty-printed with JSONView One issue I had during my code challenge was (due to my own error) not working on my own computer, which includes this extension. JSONView, a super-handy web extension for Chrome and Firefox that pretty-prints JSON in your browser Spoiler: there's an http/ https module in Node.js, but also some cool packages that mimic fetch(), or that simplify request syntax even further!īut before we get into that, I want to introduce a tool that I foolishly did not use during my technical challenge: JSONView, a super-handy web extension for Chrome and Firefox that pretty-prints JSON in your browser. (What I didn't realize is that fetch() is actually a method from the Window interface-and not having a front-end, there was no window! Awkward thing to realize at the beginning of a technical interview.)Īfter getting through the challenge, I spent this past weekend refactoring the code and experimenting with a few different ways to retrieve JSON from the web using Node.js. Since I'm still relatively new to Node.js, I did not realize that Node.js does not natively include the fetch() API, which I was used to using in my front-end JavaScript. In a recent technical challenge, I was asked to build a small Node.js app that first needed to retrieve some JSON from the web. Cover image credit: Hunter x Hunter manga by Yoshihiro Togashi, meme-ified by yours truly.
