taylorbell.com

Network Requests with node-fetch

There comes a time in every developer's life where it's time to make a network request.

Here's one way I do it with node-fetch. I like using it in tandem with Chrome's "copy as fetch" feature in the Network tab.

Install the module:

yarn add node-fetch

Create a file fetchData.js like so (assuming you're hitting a JSON endpoint)

module.exports = async function () { 
  const data = await fetch(
    "https://cooladdress.com",
    {
      credentials: "omit",
      headers: {
        accept: "application/json, text/javascript, */*; q=0.01",
        // whatever comes straight from Chrome
      },
      referrer: "https://pregame.com/game-center",
      referrerPolicy: "no-referrer-when-downgrade",
      body: null,
      method: "GET",
      mode: "cors"
    }
  ).then(result => result.json())
  
  return data
 }

And then in another file, import the module:

const fetchData = require('./fetchData')

async function processData() {
  const data = await fetchData()
}

Note that since the module exported from fetchData is an async function, we need to put it in an async function and await the value.