【发布时间】: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