【问题标题】:Fetch Request response.json() returns undefined获取请求 response.json() 返回未定义
【发布时间】:2021-11-14 21:02:01
【问题描述】:

我想向我的 Spring Boot 服务器获取一个 get 请求,然后我取回了我的 json,但是当我想返回它时,出现了一个未定义的错误。我是 Javascript 新手,所以答案可能很明显,但我找不到!

抱歉英语不好,谢谢!

代码:

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

使用异步编辑,仍然不起作用: 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;
    });
}

这是我的 react 组件函数:

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

【问题讨论】:

标签: javascript fetch fetch-api


【解决方案1】:

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

【讨论】:

  • 抱歉再次询问,但是我如何从这个异步函数中获取响应数据以将其添加到反应中的渲染中?
  • 您只需调用此行并将结果分配给变量await httpGet('https://jsonplaceholder.typicode.com/users')。我在这里使用了一个async 立即调用的函数,只是为了展示一个工作代码。如果您仍然需要帮助,请随时使用您的 react 代码创建一个单独的问题,以便社区可以更好地帮助您。
  • 在反应中我使用一个简单的组件函数来呈现我的 json 输出,但是我不能用 await 调用 httpGet 函数,因为组件函数不是异步的
  • 这已经有很多答案了,正如我在 SO 上看到的那样。即this, this & this
  • 啊,谢谢你的时间,我会调查一下
【解决方案2】:

您可以使用asyncawait 来完成此操作,这使得编写和理解代码变得容易。

这是您可以使用的示例。

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

【讨论】:

  • 工作,谢谢
猜你喜欢
  • 1970-01-01
  • 2017-02-01
  • 1970-01-01
  • 2018-08-09
  • 2022-01-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-10-26
相关资源
最近更新 更多