【问题标题】:Using Fetch in React to fetch data from server在 React 中使用 Fetch 从服务器获取数据
【发布时间】:2018-10-26 14:17:18
【问题描述】:

我正在尝试使用以下代码从服务器(Node.js)获取数据:

componentDidMount = () => {
fetch('http://localhost:3000/numberofjobs')
.then(response => response.json())
.then(numberOfJobs => {
      console.log(numberOfJobs)
})
}

这是我在 Node 中的路线:

const handleNumberOfJobs = (req, res, Register) => {
 Register.find({})
  .then(users =>  {
  const total = users.reduce((sum, { numberOfJobs }) => sum + 
  numberOfJobs, 0);
  console.log(total);
  })
  .then(response => res.json(response))
}

我遇到的一个问题是前端 console.log 没有显示在控制台中,我不知道为什么。在服务器端,当页面加载时,它会执行 console.log 总和和所有内容,所以它正在工作,所以我相信我在使用 React 时做错了。我想将此信息带到我的前端,以便我可以将其显示在页面上。

非常感谢!!

【问题讨论】:

  • 旁注:您没有在fetch 调用中检查错误。这是一个常见的错误,I wrote it up on my anemic little blog.
  • 除了对fetch 的错误检查(这不太可能是问题)之外,这看起来很好,只是让componentDidMount 成为这样的箭头函数有点不寻常。请使用 minimal reproducible example 来更新您的问题,以展示问题,最好是使用 Stack Snippets([<>] 工具栏按钮)的 runnable 问题。 Stack Snippets 支持 React,包括 JSX; here's how to do one。 (可以使用setTimeout模拟fetch。)
  • 尝试添加.catch(error => console.log(error))。它可能会以某种方式抛出错误,并且无法到达您在.then 中的console.log。
  • @JamesIves - 但通常情况下,您会在控制台中收到“未处理的拒绝”错误...
  • 你确定吗,.then(response => res.json(response)) 会返回响应。我认为在第一个 then 中返回响应 (res.json(response)),你有 console.log 会起作用。

标签: javascript node.js reactjs express


【解决方案1】:

TL;DR

在您的服务器端代码中使用箭头函数的隐式返回有一个错误。

解决方法是在第一个 .then(...) 处理程序中添加一个 return total;

详情

首先,让我们把它说出来:我同意 cmets 关于不要忽视错误检查的观点! (无论是fetch 还是其他任何东西。)

无论如何:您在 .then(...) 处理程序中使用箭头函数。但是第一个语句中的最后一个语句是console.log(total)。该调用的返回值为undefined,它成为箭头函数的隐式返回值。然后,Promise 将其作为 response 的值传递给您的第二个 .then(...) 处理程序。 (您可以通过在第二个 .then(...) 处理程序中添加 console.log(response) 来验证这一点。

解决方法是在第一个 .then(...) 处理程序中添加一个 return total;

const handleNumberOfJobs = (req, res, Register) => {
  Register
    .find({})
    .then(users => {
      const total = users.reduce(
        (sum, { numberOfJobs }) => sum + 
            numberOfJobs, 0
      );
      console.log(total);   // <-- returns undefined
      return total;         // <-- pass on to next promise
    })
    .then(response => {
      // console.log(response);  // if you're curious
      res.json(response)
    })
  }
}

个人提示:缩进/整理代码以便于维护。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-26
    • 1970-01-01
    • 1970-01-01
    • 2019-01-05
    • 2018-03-05
    相关资源
    最近更新 更多