【问题标题】:Not able to connect React App with a NodeJS in Backend无法在后端将 React App 与 NodeJS 连接
【发布时间】:2022-12-29 03:37:53
【问题描述】:

我正在尝试从后端获取数据,但出现错误 fetchData.map is not a function
如果有人能解释一下为什么fetchData.map is not a function

这是反应代码

    function App() {
        const [fetchData, setFetchData] = useState([]);
        useEffect(() => {
            fetch("/api")
                .then((res) => res.json())
                .then((data) => {
                    console.log(data);
                    setFetchData(data);
                });
        }, []);
        return <>{fetchData.map(data=> <div>data</div>)}</>;
    }

这是 NodeJS 代码


    const express = require("express");
    const app = express();
    const test = require("./test.json");
    
    PORT = 3001;
    
    app.get("/api", (req, res) => {
        res.json(test);
    });
    
    app.listen(PORT, () => console.log(`Server Started on ${PORT}`));

【问题讨论】:

  • 您可以发布请求的回复吗?日志显示什么?
  • 在 NodeJS 中将 res 更改为 req getting GET http://localhost:3000/api 500 (Internal Server Error)
  • 你的 fetchData 不是数组,不要使用地图。使用Object.keys(fetchData).map(item =&gt; fetchData[item])

标签: javascript node.js reactjs server backend


【解决方案1】:
  function App() {
        // Change it to null by default
        const [fetchData, setFetchData] = useState(null);
        useEffect(() => {
            fetch("/api")
                .then((res) => res.json())
                .then((data) => {
                    console.log(data);
                    // wrap data with [] to make it iterable
                    setFetchData([data]);
                });
        }, []);

        // Check if value is present before mapping 
        return <>{fetchData?.map(data=> <div>data</div>)}</>;
    }

【讨论】:

  • 我试过这个但没有用
  • 您应该在映射列表 <>{fetchData?.map(data=> <div>data</div>)}</> 之前检查该值是否不为空
  • 谢谢,现在我明白了如何以 3 种不同的格式从 json 中获取数据
【解决方案2】:

因为您的响应是对象而不是数组。

您可以对数组使用映射、过滤器和 ...

【讨论】:

    猜你喜欢
    • 2020-02-29
    • 2018-06-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-22
    • 2019-11-18
    相关资源
    最近更新 更多