Fetch is a relatively new addition to the browsers which allows us to avoid adding libraries to our browser-based applications. (You can learn more from Using the New JavaScript Fetch HTTP API blog article).
As you may have noticed, fetch doesn’t work in Node.js. If you attempt to use it you get an error like the below one
(node:21368) UnhandledPromiseRejectionWarning: ReferenceError: fetch is not defined
at createObj(C:\source\scratch\api-caller.js:58:28)
at Object. (C:\source\scratch\api-caller.js:108:1)
at Module._compile (internal/modules/cjs/loader.js:1137:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1157:10)
at Module.load (internal/modules/cjs/loader.js:985:32)
at Function.Module._load (internal/modules/cjs/loader.js:878:14)
at Function.executeUserEntryPoint as runMain
at internal/main/run_main_module.js:17:47
(node:21368) UnhandledPromiseRejectionWarning: Unhandled promise rejection.
This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch().
To terminate the node process on unhandled promise rejection, use the CLI flag --unhandled-rejections=strict
(see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:21368) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
The fetch API isn’t implemented in Node, so you need to use a package that implements it and then use that.
There are quite a few different modules available, I’m tending to use node-fetch as it more resembles the native fetch is ES6. The node-fetch package is pretty lightweight and is quite a bit smaller than axios.
So, how do we use node-fetch then?
We need to install the node package using npm or yarn. I prefer to use npm as it works well enough for me (and it comes with Node on Windows!) To install it, I simply need to type the following command into the terminal
npm i node-fetch
It will run for a moment or two and then show results like the below image
Using the library inside of our code is actually pretty easy. For the most part, I just require it at the top of my modules and I’m good to go.
'use strict'
const fetch = require('node-fetch')
Wrapping it Up
For now, Node.js doesn’t implement fetch. Hopefully, some day it is added in and we no longer need to add another dependency.
For now, I recommend using a dependency like node-fetch or looking at request or axios.
Also published on Medium.