【问题标题】:Fetch data from PostgreSQL into React从 PostgreSQL 获取数据到 React
【发布时间】:2022-06-19 14:27:40
【问题描述】:

我正在尝试执行测试任务,但我被禁止使用库和插件来处理 DB、ORM。

我需要从 PostgreSQL 表中获取数据并显示在 React 组件中,但我不知道如何从节点中获取数据以进行响应。

这是我从数据库中获取数据的方式:

const { Client } = require("pg");

const client = new Client({
  host: "localhost",
  user: "postgres",
  port: 5432,
  password: "postgres",
  database: "welbex-test",
});

client.connect();

client.query(`SELECT * from products`, (err, res) => {
  if (err) {
    console.log(err.message);
  } else {
    console.log(res.rows);
  }
  client.end;
});

这是我尝试获取数据的方式:

  useEffect(() => {
    const fetchProducts = async () => {
      setLoading(true);
      const res = await axios.get(
        "http://localhost:3000/src/Components/API/connect"
      );
      setProducts(res.data);
      setLoading(false);
    };
    fetchProducts();
  }, []);

【问题讨论】:

    标签: node.js reactjs postgresql


    【解决方案1】:

    您需要设置服务器。 Express 是一种流行的导出 api 的服务器。然后将端点更改为您的服务器以获取数据。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-12-15
      • 1970-01-01
      • 2016-08-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多