Fetching Data from URL
npm i node-fetch --save
To install node-fetch and add the line:
const fetch = require(‘node-fetch’);
At the top of your program. Next add the code:
What’s up everyone. Welcome to fetching data from a URL. Here we’re going to write the actual code that will fetch the data we want, and we’re going to use our asynchronous functions that promises to do so. Actually, before we get started we should probably install that fetch API.
So assuming that you are in your project directory, if not then navigate there now. We’re just going to use a simple npm command to install what’s called node fetch. So we’re going to do npm i node-fetch –save like so. Okay, so we’ll not worry about the warning or anything as long as we see added 1 package then we are good to go. If you open up your packages.json – so let’s go back here if we open up packages.json we should see node-fetch there.
So now we’ll need to add the fetch API here. And we’re gonna do so by creating a constant called fetch this is going to be equal to require node-fetch. Okay, so now we have the fetch function and can use this to retrieve the data in our URL. So lets actually go back to chrome. This is the data that we want. This is exactly what the format of the data we want comes back in.
So we actually want to store the results of this in a variable. We’re going to call this a response. Response equal to fetch(URL). This is where things get interesting, because this is an asynchronous function, we’re going to actually do await fetch(URL). So the fetching of the data is going to take some time. We don’t want this blocking up the main thread while it’s fetching the data. And that’s why we’re doing await fetch, because fetching the URL or fetching dates from this URL may take some time. So we’re basically just going to say response only takes on the value after fetch has retrieved the data.
Okay so from here, we have the response but we want to make sure that it’s JSON data. So this will just come back as an object that needs to be decoded. So what we’re gonna do is we’re gonna create a variable, jsonResponse, and we’re gonna set this equal to again await – because it may take some time – and we’re going to get our response and we’re going to call the JSON function. So this is gonna convert our response to JSON and then let’s say we just want to print out a simple console.log and we’re going to stringify this data.
So we’re gonna call upon a JSON method called stringify and we’re just gonna pass in our jsonResponse. So we’re gonna call upon fetchData and we’re going to pass in that URL. Now this will do the printing. We can actually give this a save and we can run it. This is really promising, you can see that we’re getting back this huge string of data and has essentially exactly the same data as we see here.