简体   繁体   中英

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:

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;
    });
}

This is my react component function:

 function Admin(){
    const data =  httpGet('https://jsonplaceholder.typicode.com/users'); // Not Working
    console.log(data);  
    return(
        <div>
            <h1> Admin Page</h1>
        </div>
    )
}

 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); })();

You can do this with async and await which makes easy to write and understand the code.

Here is the sample, that you can use.

 const httpGet = async (theUrl) => { const response = await fetch(theUrl, { method: "GET", headers: { Accept: "application/json", "Content-Type": "application/json" } }); return response.json(); }; // calling the method (async () => { const data = await httpGet("https://jsonplaceholder.typicode.com/posts/1") console.log("response data is: ", data) })()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM