In the previous exercise, we set up the POST request by providing the endpoint and the object containing all the necessary information. In this exercise, we’ll handle the response.
The request returns a Promise which will either be resolved or rejected. If the promise resolves, we can check and return that response. We will chain another
.then() method and handle the returned JSON object and display the information to our webpage.
Let’s implement this knowledge into our code!
Remember that if you reset the exercise at any point, you will have to paste in your API key again at the top!
.then() method at the end of the
fetch() function we wrote in the previous exercise. As its first argument, pass an arrow function as a callback that takes
response as its single parameter.
Inside the callback function of the
.then() method, use a conditional statement to check the value of the
ok property of
response. If it evaluates to a truthy value, return
Run the code.
Below the curly braces of the conditional statement,
throw a new
Error in case
response.ok is falsy.
The error message should be
As the second argument of the
.then() method, add another arrow callback function that takes
networkError as a single parameter.
networkError.message inside of the callback function.
By adding this second callback, you’re safeguarding yourself in the rare event that the network returns an error!
.then() method to the end of the previous
Pass in an anonymous arrow function as an argument for our second
.then(). This callback function will take
jsonResponse as its single parameter.
Inside the callback function, call
renderResponse() and pass in
renderResponse() helper function can be viewed at public/helperFunctions.js.
Run the code.
Put in any URL in the text field, and then click the shorten button on the webpage. Make sure you include the entire link, including