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

标签 node.js reactjs api server axios

我不确定是什么问题。我知道 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/

相关文章:

javascript - 无法在 node/express/pug 应用程序中获取 css

javascript - 如何将元素的属性传递给 React 中的函数?

c++ - 使用 C++ 在 Windows 中输入笔

django - 使用 django 作为 ionic 应用程序后端时出现 CORS 错误

bash - API 调用在浏览器中有效,但在 curl/wget 中无效

javascript - 如何像 JSFiddle 中那样创建唯一的 session ID?

node.js - 读写 "NodeJs"中的 XML Node 值

java - 语法错误: Unexpected token ILLEGAL in Node Javascript

reactjs - React JSX 中的 try-catch 语句

javascript - 在 React 中渲染多个条件三元运算符