【发布时间】: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 => fetchData[item])
标签: javascript node.js reactjs server backend