FAQ: Requests II - fetch() GET Requests III

I had the same problem, but if you carry on to the next excercise it then all starts to make sense.

Hey guys, I cant find any info on why we need this second argument {cache: ‘no-cache’}. Can someone explain what exactly going on here, please ?

thank you

1 Like

I thought I was just the only one haha

2 Likes

Hey Guys,
I tried executing the Network Requests locally on my system after completely finishing the Network Requests | & ||.
So basically when i run node index.js in terminal ,im getting Reference Error: document is not defined.
i googled about it and found that in nodejs doesnt have the DOM representation. Then tried many to get past this error by installing ESLint, installing JSDom package but could not figure it out …
@mtf @midlindner and anybody who know’s the solution ,Please help.

I’m far from expert here, but if you’re trying to run the wordsmith app that is built in the exercises, doing it from Node is a bit involved. I found this tutorial which seems to explain it fairly well. What you need to run is the index.html file. The JavaScript code is executed after you click the Submit button on the web page. You can do this more simply by creating the same file structure you have in the exercise on your own computer, and then opening the index.html file with any web browser. You could create a new folder named whatever you like, then copy and paste the files from the exercise into it. Something like:


Inside the Public folder:

Same here, i dont understand why it isnt running. I got checked for all the instructions but yet still nul at the end. The whole lesson about this making request is a little bit complicated from the others, anyways this is my code incase anyone thinks i made a mistake:

const url = ‘https://api.datamuse.com/words’;
const queryParams = ‘?sl=’;

// Selects page elements
const inputField = document.querySelector(’#input’);
const submit = document.querySelector(’#submit’);
const responseField = document.querySelector(’#responseField’);

// AJAX function
const getSuggestions = () => {
const wordQuery = inputField.value;
const endpoint = (url + ’ ’ + queryParams + ’ ’ + wordQuery);
fetch(endpoint, {cache: ‘no-cache’})
.then((response) => {
if(response.ok) {
return response.json();
}
throw new Error(‘Request failed!’);
}, (networkError) => {
console.log(networkError.message);
});
};

// Clears previous results and display results to webpage
const displaySuggestions = (event) => {
event.preventDefault();
while(responseField.firstChild){
responseField.removeChild(responseField.firstChild);
}
getSuggestions();
};

submit.addEventListener(‘click’, displaySuggestions);

Why is the helper function js file included after the main js file?

  <script src="public/main.js"></script>
  <script src="public/helperFunctions.js"></script>
</body>

Hello!

I was wondering why is it that before we return response.json(); in the conditional, we first perform renderJsonResponse() ?

Thanks in advance!

1 Like

Stuck on question 7.

Inside the success callback function, create a conditional statement that checks if the ok property of the response object evaluates to a truthy value. If so, call the function renderJsonResponse() and pass in response as an argument. Then, run your code.

Then type in a word to and click the submit button to view the JSON that came back. The status of the promise return from fetch() will be resolved.

The code for renderJsonResponse() can be viewed at public/helperFunctions.js .

This is my code:

// Information to reach API

const url = 'https://api.datamuse.com/words'

const queryParams = '?sl='

// Selects page elements

const inputField = document.querySelector('#input');

const submit = document.querySelector('#submit');

const responseField = document.querySelector('#responseField');

// AJAX function

const getSuggestions = () => {

const wordQuery = inputField.value;

const endpoint = `${url}${queryParams}${wordQuery}`;

fetch(endpoint,{cache: 'no-cache'}).then(response => {

    if (response.ok) {

      return renderJsonResponse(response);

     // return response.json();

    }

    })

   

// Clears previous results and display results to webpage

const displaySuggestions = (event) => {

  event.preventDefault();

  while(responseField.firstChild){

    responseField.removeChild(responseField.firstChild);

  }

  getSuggestions();

};

submit.addEventListener('click', displaySuggestions);

The solution doesnt even use renderJsonResponse. Please advise.

I think the problem lies in the line:

return renderJsonResponse(response);

As you can see in public/helperFunctions.js, renderJsonResponse() does not return a value itself, as its job is merely to manipulate the HTML code:

// Renders the JSON that was returned when the Promise from fetch resolves.
const renderJsonResponse = (res) => {
  // Creates an empty object to store the JSON in key-value pairs
  let rawJson = {};
  for(let key in res){
    rawJson[key] = res[key];
  }
  // Converts JSON into a string and adding line breaks to make it easier to read
  rawJson = JSON.stringify(rawJson).replace(/,/g, ", \n");
  // Manipulates responseField to show the returned JSON.
  responseField.innerHTML = `<pre>${rawJson}</pre>`;
}

Instead, what you need to do inside the conditional is merely to call the function, without the usage of the return keyword, like so:

fetch(endpoint,{cache: 'no-cache'}).then(response => {
    if (response.ok) {

      renderJsonResponse(response);

    }

 })

Doing this will result in this appearing in the browser:

{"type":"cors", 
"url":"https://api.datamuse.com/words?sl=hello", 
"redirected":false, 
"status":200, 
"ok":true, 
"statusText":"OK", 
"headers":{}, 
"body":{}, 
"bodyUsed":false}

This is the JSON that the server sent us back as a response from our GET request, and it contains a lot of metadata that is really not a part of the final solution, which is why this function isn’t used in it.

Hope this helps. Cheers

Hi everyone,
in “fetch() GET Requests III” we are calling the “fetch” method with two functions, namely one for success and one for error. However, I don’t understand why we are placing both the success and error function into the same “then” block as opposed to having a “catch” block after the “then” block. I have written my alternative in the following and was wondering whether or not there is any difference in the two approaches or if my approach simply includes “syntactic sugar”.
Thanks! :slight_smile:

CODECADEMY APPROACH:

fetch(endpoint, {cache: "no-cache"})
    .then((response) => {
      if (response.ok){
        return response.json();
      }
      throw new Error("Request failed!");
    }, (networkError) => {
      console.log(networkError.message);
    }
    )

MY APPROACH:

fetch(endpoint, {cache: "no-cache"})
    .then((response) => {
      if (response.ok){
        return response.json();
      }
      throw new Error("Request failed!");
    }
    .catch((networkError) => {
       console.log(networkError.message)
   }
  )
1 Like

same here. question #6 looks weird it only says: Chain a .then() method to the fetch() function.
Pass it a success arrow callback function as an argument.
The callback function should take response as its single parameter.

I tried the 1st one too it says error but the if response is only created at #7 why am I wrong? keeps me wondering. someone elaborate this please thanks!