如何获取 Mysql 数据并将其显示到以 Node JS 作为后端的 ReactJS 前端?

How can I Fetch and display Mysql data into ReactJS front end with Node JS as backend?

试图弄清楚如何从 mysql 获取数据并将其显示在 ReactJS 中。我在后端使用 NodeJS 和 express。我尝试了在 Internet 上找到的代码片段,但它没有按预期工作。

这是我在 运行 React 应用程序时得到的结果。

TypeError: http.ServerResponse is undefined

我的 NodeJS 代码

//require mysql, http and express
//const connection = createConnection({with host, user, pass, db});
const app = express();
app.get('/posts', function(request, result){
    connection.connect();
    connection.query("SELECT * FROM 'some_table';", function(err, results, fields){
         if(err) throw err;
        result.send(results);
    })
    connection.end();
})
app.listen(3000);

我的 React 代码

class Display extends React.Component{
    constructor(props){
        super(props);
        this.state={ posts : [] };

        fetch('http://localhost:3000/posts/')
            .then(response =>{
                response.json();
            })
            .then(posts => {
                this.setState({posts})
            })
            .then( (err) => {
                console.log(err);
            })
    }
    render(){
        return(
            <div>
                <ul>
                    {this.state.posts.map( post => 
                    <p>
                        <li>Some Text_1: {post.db_col_1}</li>
                        <li>Some Text_2: {post.db_col_2}</li>
                        <li>Some Text_3: {post.db_col_3}</li>
                    </p>
                    )}
                </ul>
            </div>
        )
    }
}
export default Display;

根据 React documentation,React 组件的构造函数在挂载之前被调用。它还声明如下:

Avoid introducing any side-effects or subscriptions in the constructor. For those use cases, use componentDidMount() instead.

您应该在 componentDidMount 中进行 API 次调用。根据 React 文档:

If you need to load data from a remote endpoint, componentDidMount is a good place to instantiate the network request.

您的代码应如下所示:

import React from "react";

class Display extends React.Component {
  constructor(props) {
    super(props);

    this.state = { posts: [] };
  }

  componentDidMount() {
    fetch("http://localhost:3000/posts/")
      .then(response => {
        response.json();
      })
      .then(posts => {
        this.setState({ posts });
      })
      .then(err => {
        console.log(err);
      });
  }

  render() {
    return (
      <div>
        <ul>
          {this.state.posts.map(post => (
            <p>
              <li>Some Text_1: {post.db_col_1}</li>
              <li>Some Text_2: {post.db_col_2}</li>
              <li>Some Text_3: {post.db_col_3}</li>
            </p>
          ))}
        </ul>
      </div>
    );
  }
}

export default Display;

如果您的后端 Node.js 应用程序返回正确的数据,以上代码段将起作用。

您的代码需要一些错误处理和 CORS 策略。所以我建议你这样做;

确保您的后端已启动并且 运行

您需要在后端检查您的端口。

确保数据库启动并且运行

您需要检查您的数据库连接是否存在。每次发出请求时都无需连接到数据库。所以最好连接一次。

通过 Postman 或任何其他工具尝试 API 结果

您需要确保可以通过任何其他客户端应用访问您的后端。您还可以打开浏览器并通过在浏览器“http://localhost:3000/posts

中打开 link 来测试您的 API

为您的后端激活 CORS 策略。

SPA 需要 CORS 策略才能向后端发出请求。您可以为此使用 cors npm 库,也可以创建自己的规则。

使用抓取库

您可以使用 fetch,但并非所有浏览器都支持它。在您的客户端代码上使用 Axios 或任何其他请求工具会很好。

const cors = require('cors')
const app = express();

const mysql = require('mysql');

const connection = mysql.createConnection({
  host: "localhost",
  user: "yourusername",
  password: "yourpassword"
});

connection.connect(function(err) {
  if (err) throw err;
  console.log("Connected!");
});

app.use(cors());

app.get('/posts', (req, res) => {
  connection.query("SELECT * FROM 'some_table';", (err, results, fields) => {
    if(err) throw err;
    res.send(results);
  });
});

app.listen(3000, (error) => {
  if (err) throw err;
  console.log(`App listening on port ${port}!`)
});

参考提到 password: "yourpassword" 的其他答案,检查您是否为用于连接到数据库的用户设置了密码。

我遇到了 PostgreSQl 的问题,但这在其他地方可能也是一样的:全新安装不会自动为超级用户设置密码,也不会为您创建的任何其他用户自动设置密码超级用户登录。

显示的错误并未暗示问题,例如 TypeError: Cannot read property 'rows' of undefined 似乎解决了代码中“行”的错误,但实际上只是缺少密码的错误。

如果没有设置密码,您可以随便尝试,您将无法访问后台。在 PostgreSQL 中,我必须遵循 .