Javascript 使用Fetch-in-React从服务器获取数据
我正在尝试使用以下代码从服务器(Node.js)获取数据:Javascript 使用Fetch-in-React从服务器获取数据,javascript,node.js,reactjs,express,Javascript,Node.js,Reactjs,Express,我正在尝试使用以下代码从服务器(Node.js)获取数据: componentDidMount = () => { fetch('http://localhost:3000/numberofjobs') .then(response => response.json()) .then(numberOfJobs => { console.log(numberOfJobs) }) } 这是我在节点中的路线: const handleNumberOfJobs = (re
componentDidMount = () => {
fetch('http://localhost:3000/numberofjobs')
.then(response => response.json())
.then(numberOfJobs => {
console.log(numberOfJobs)
})
}
这是我在节点中的路线:
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没有显示在控制台中,我不知道为什么。在服务器端,当页面加载时,它会记录sum和所有内容,因此它工作正常,所以我相信我在React上做错了什么。我想把这个信息带到我的前端,这样我就可以在页面上显示它了
非常感谢 TL;DR
在服务器端代码中如何使用箭头函数的隐式返回是一个错误
解决方法是只添加一个返回总数代码>在第一个处理程序中,然后(…)
处理程序
详细信息
首先,让我们把它说出来:我同意关于不忽略错误检查的评论!(可以是fetch
或其他任何东西。)
无论如何:在处理程序中使用箭头函数。然后(…)
处理程序。但是第一条语句中的最后一条语句是console.log(total)
。该调用的返回值为undefined
,它将成为arrow函数的隐式返回值。然后,承诺将其作为第二个处理程序中的响应的值进行传递。然后(…)
处理程序。(您可以通过在第二个处理程序中添加console.log(response)
来验证这一点。然后(…)
处理程序
修复方法是只在第一个中添加一个返回总数;
。然后(…)
处理程序:
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)
})
}
}
const handleNumberOfJobs=(请求、恢复、寄存器)=>{
登记
.find({})
。然后(用户=>{
const total=users.reduce(
(sum,{numberOfJobs})=>sum+
作业数,0
);
console.log(总计);//旁注:您没有检查fetch
调用中的错误。这是一个非常常见的错误。除了检查fetch
上的错误(这可能不是问题)之外,这看起来很好,只是将componentDidMount
设置为这样的箭头函数有点不寻常。请更新您的que继续演示问题,理想情况下是使用堆栈代码段(工具栏按钮)的可运行代码段。堆栈代码段支持React,包括JSX;(可以使用setTimeout
模拟fetch
)尝试添加.catch(错误=>console.log(错误))
。它可能会以某种方式抛出一个错误,而没有到达中的console.log。然后@JamesIves-通常情况下,您会在控制台中收到一个“未处理的拒绝”错误…您确定吗,。然后(response=>res.json(response))
将返回response。我认为返回response(res.json(response)
)在第一个中,然后是,在那里您有控制台。log
可以工作。