Let’s get hands-on! We’ll be using it for our practice.
JSON is a structured text-based format for the transmission of data, between web servers and clients.
This JavaScript code defines a constant variable requestUrl
that stores the URL of a JSON file containing some raw JSON data. We create a new Request
object with the requestUrl
as its argument to fetch the data from the specified URL.
A look at the JSON data
Next, to obtain the JSON, we use an API called fetch()
to send the request from the client and retrieve the data from the URL. The fetch()
function returns a Promise that resolves to a Response
object, which represents the response to the request. The await
keyword is used to pause the execution of the code until the Promise is resolved and the Response
object is available.
The Response
object, which can be used to access the data returned by the server.
Overall, this code is a common pattern used in JavaScript to fetch data from a remote URL using the fetch()
function and the Request
API.
We’ll extract the data from the Response
object. The json()
method of the Response
object is called on the response
variable, which returns a promise that resolves to the result of parsing the response body as JSON. We parse it into JSON as the transmitted data is of type string.
Next, we wrap this in an async function to return a promise
In JavaScript, the keyword async
indicates that a function is asynchronous. When a function is declared with async
keyword, it automatically returns a promise. The promise is resolved with the value returned by the async function or rejected with an uncaught exception.
Now we write two functions to get the data into our HTML pages. These functions will use the response object that we generated using the data we received from the request URL.
<!DOCTYPE html>
Our superheroes