gpt4 book ai didi

javascript - 在React中使用Fetch从服务器获取数据

转载 作者:行者123 更新时间:2023-12-03 00:51:52 25 4
gpt4 key购买 nike

我尝试使用以下代码从服务器(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 上做错了。我想将此信息带到我的前端,以便我可以将其显示在页面上。

非常感谢!!

最佳答案

TL;DR

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

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

详细信息

首先,让我们说一下:我同意关于不要忽视错误检查的评论! (无论是 fetch 还是其他任何东西。)

无论如何:您可以在 .then(...) 处理程序中使用箭头函数。但第一个语句中的最后一个语句是console.log(total)。该调用的返回值是未定义,它成为箭头函数的隐式返回值。然后,Promise 将其作为第二个 .then(...) 处理程序中的 response 值传递。 (您可以通过在第二个 .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)
})
}
}

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

关于javascript - 在React中使用Fetch从服务器获取数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53010707/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com