Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Fetch Request response.json() returns undefined

I want to fetch a get request to my spring boot server, and i get my json back, but when i want to return it, there is an undefined error. I am new to Javascript, so the answer is probably obvious, but i cant find it!

Sry for bad english and thanks in regards!

Code:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

function httpGet(theUrl)
{
    fetch(theUrl,
    {
        method: "GET",
      headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json',
      },
    })
    .then (response => response.json())
    .then(response => {
        console.log(response); // Logs the json array
        return response; // Returns undefined
    });
}

Edit with async, still does not work:
https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch

async function httpGet(theUrl)
{
    const response = await fetch(theUrl,
    {
        method: "GET",
        headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json',
      },
    });
    const jsonResponse = await response.json()
    .then(data => {
        return data;
    });
}

>Solution :

function httpGet(theUrl) {
  return fetch(theUrl, {
      method: "GET",
      headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json',
      },
    })
    .then(response => response.json());
}


(async() => {
  const response = await httpGet('https://jsonplaceholder.typicode.com/users');
  console.log(response);
})();
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading