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

12,159

Solution 1

Your code needs some error handling and CORS policy. So I would recommend to you do;

Make sure your backend is up and running

You need to check your ports on backend.

Make sure database up and running

You need to check your connection is there for your database. No need to connect to your database each time when you make request. So better to connect once.

Try your API result via Postman or any other tool

You need to make sure your backend is reachable via any other client app. You can also open your browser and test your API with opening the link in browser 'http://localhost:3000/posts'

Activate CORS policy for your backend.

SPA needs CORS policy to make a request to the backend. You can use cors npm library for that or you can create your own rules.

Use a fetch library

You can use fetch but it is not supported by all browsers. It would be nice to Axios or any other request tool on your client code.

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}!`)
});

Solution 2

According to the React documentation, The constructor for a React component is called before it is mounted. It also states the following:

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

You should do API calls in componentDidMount. According to React documentation:

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

Your code should look like the following:

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;

The above snippet will work provided your back-end Node.js application is returning the proper data.

Share:
12,159
IVAN PAUL
Author by

IVAN PAUL

Updated on June 04, 2022

Comments

  • IVAN PAUL
    IVAN PAUL almost 2 years

    Trying to figure out on how to fetch data from mysql and display it in ReactJS. I'm using NodeJS on the backend along with express. I tried a code snippet found on the internet but it doesn't work as it is expected.

    Here's what i get when i run the react app.

    TypeError: http.ServerResponse is undefined
    

    My NodeJS code

    //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);
    

    My React code

    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;
    
    • Leafyshark
      Leafyshark about 4 years
      Have you considered trying axios, ajax, fetch?
    • IVAN PAUL
      IVAN PAUL about 4 years
      Maybe i didn't get you, but I am using fetch in the react part of my code.
    • Leafyshark
      Leafyshark about 4 years
      And have you followed these instructions: w3schools.com/nodejs/nodejs_mysql.asp?
  • Nirmalya Ghosh
    Nirmalya Ghosh about 4 years
    What is the data that your back-end is returning? If this.state.posts is undefined, it means that your back-end isn't returning any posts array in the response.
  • IVAN PAUL
    IVAN PAUL about 4 years
    Backend is returning data, its just that the this.state.posts cannot be accessed from where it is called.
  • Nirmalya Ghosh
    Nirmalya Ghosh about 4 years
    .then(posts => { this.setState({ posts }) }) In this line, your posts are getting set in the React state. Can you check if the state is getting populated properly? If you share a CodeSandbox or Codepen link, I can help you more with this.
  • IVAN PAUL
    IVAN PAUL about 4 years
    Thanks @hurricane, I now know what I am actually doing, but the code still doesn't work, it is working on the server but the client is not getting the response back. All it says that the cors request failed.
  • hurricane
    hurricane about 4 years
    @IVANPAUL are you using app.use(cors());
  • IVAN PAUL
    IVAN PAUL about 4 years
    Yes I'm using app.use(cors()); statement. when I run the Element Inspector for network diagnostics it show no response headers and response tab also shows "No Response". It is working fine when i pass a simple text, but not fetching the json data.