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

问题描述 投票:0回答:2

[试图弄清楚如何从mysql获取数据并将其显示在ReactJS中。我在后端和Express一起使用NodeJS。我尝试了在互联网上找到的代码段,但由于预期的原因,该代码段无法正常工作。

这是我运行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;

亲切的帮助,非常感谢。

mysql node.js reactjs express httpserver
2个回答
0
投票

根据React documentation,React组件的构造函数在安装之前被调用。它还指出以下内容:

避免在构造函数中引入任何副作用或订阅。对于这些用例,请改用componentDidMount()。

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

如果需要从远程端点加载数据,componentDidMount是实例化网络请求的好地方。

您的代码应如下所示:

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应用程序返回正确的数据的情况下起作用。


0
投票

您的代码需要一些错误处理和CORS政策。因此,我建议您这样做;

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

您需要检查后端的端口。

确保数据库正常运行

您需要检查数据库是否存在连接。每次发出请求时都不需要连接到数据库。因此最好连接一次。

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

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

中的链接,打开浏览器并测试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}!`)
});
© www.soinside.com 2019 - 2024. All rights reserved.