In the previous exercise you’ve positioned yourself to make the POST request by providing the endpoint and the object containing all the necessary information. In this exercise you’ll handle the response.
The request returns a Promise which will either be resolved or rejected. If the promise resolves, you can use that information and the
ok status. Let’s implement that knowledge into your code!
If you reset the exercise at any point, you will have to paste in your API key again at the top!
.then() method to the end of the
fetch() function you wrote in the previous exercise. As its first argument, pass it an arrow function as a callback that takes
response as its single parameter.
Inside the block of the function you made in Step 1, use a conditional statement to check the value of the
ok property of
response. If it evaluates to a truthy value, call
renderJsonResponse() and pass in
Run the code.
Now, if you post a URL, you should see the object that was sent back!
renderJsonResponse() is a helper function found in public/helperFunctions.js.
Great, now that you see the raw object, you will need to pass the JSON to the next
renderJsonResponse(response) and replace it with
Below the curly braces of the conditional statement,
throw a new
Error in case
response.ok is falsy.
The message the error should raise is
Outside of the code block from the first callback function you wrote, add another arrow callback function that takes
networkError as a single parameter.
networkError.message inside of the callback function you just wrote.
By adding this second callback, you’re safeguarding yourself in the rare event that the network returns an error!