gpt4 book ai didi

node.js - 从 fetchData 返回的 Promise 被忽略

转载 作者:行者123 更新时间:2023-12-04 15:23:14 24 4
gpt4 key购买 nike

我不确定是什么问题。我知道 axios 无法从 api 获得响应,但我不明白为什么。

我的 nodejs 后端服务器文件:

import data from './data';

const app = express();
app.get("/api/products", (req, res) => {

res.send(data.products);
})
app.listen(5000, () => {console.log("Server started at http://localhost:5000")})

我可以在 localhost:5000 上看到数据,但当我尝试在前端呈现数据时却看不到。我收到一条错误消息“无法获取 api/产品”

前端api调用:

const [products, setProducts] = useState([]);

useEffect(() => {
const fetchData = async () => {
const { data } = await axios.get("/api/products");
setProducts(data);
}
fetchData();
return () => {
//
};
}, [])

前端的package.json:

{
"name": "frontend",
"proxy": "http://127.0.0.1:5000",
"version": "0.1.0",
"private": true,
"dependencies": {
"@testing-library/jest-dom": "^4.2.4",
"@testing-library/react": "^9.5.0",
"@testing-library/user-event": "^7.2.1",
"axios": "^0.19.2",
"react": "^16.13.1",
"react-dom": "^16.13.1",
"react-router-dom": "^5.2.0",
"react-scripts": "^2.1.8"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
"eslintConfig": {
"extends": "react-app"
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
}
}

网络日志: enter image description here

最佳答案

fetchData 返回 Promise。您需要使用 awaitthen 来解决它。并且您需要从 useEffect Hook 中提取您的方法:

const fetchData = async () => {
const { data } = await axios.get("/api/products");
return data;
}

useEffect(() => {
fetchData().then(data => setProducts(data));
}, []);

关于node.js - 从 fetchData 返回的 Promise 被忽略,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62857709/

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