Petra Jakubcova
Petra Jakubcova

Reputation: 105

How to fetch data from MySQL database with Node

I'm new to react, developing a recipe-app and I got a problem while displaying the data from MySQL database. The connection was created successfully, however, I'm not sure about how to reach the data. When I run node server.js in my terminal, I get "connected", When I visit the localhost:8080/users, I get "This site can't be reached" message and in my terminal:

`events.js:187
      throw er; // Unhandled 'error' event
      ^

Error: Cannot enqueue Handshake after already enqueuing a Handshake.`

I'm a little stuck here. Anyone knows a solution or direct me a little bit? Thank you so much!

Server.js

const express = require('express');
const app = express();
const PORT = 8080;

const mysql = require('mysql');
const connection = mysql.createConnection({
  host: 'localhost',
  user: 'root',
  password: 'root',
  database: 'recipe_app'
});
connection.connect((err) => {
  if (err) throw err;
  console.log('Connected!');
});

//creating route for the app
app.get('/users', (req, res) => {
    connection.connect();
    connection.query('SELECT * from users', function(err, rows, fields) {
        if (!err) {
            res.send(JSON.stringify(rows));
        } else {
            console.log('Error while performing Query.');
        }
    });
    connection.end();
});

//making server listen to request
app.listen(PORT, () => {
    console.log(`Server running at : http://localhost:${PORT}/`);
});

Upvotes: 0

Views: 2280

Answers (2)

Cristopher Namchee
Cristopher Namchee

Reputation: 92

You're trying to reconnect to mysql after the connection has been established. See my comments on the code below

const connection = mysql.createConnection({
  host: 'localhost',
  user: 'root',
  password: 'root',
  database: 'recipe_app'
});
connection.connect((err) => { // This creates the connection
  if (err) throw err;
  console.log('Connected!');
});

And when you're trying to resolve your GET routes, you're trying to connect again

//creating route for the app
app.get('/users', (req, res) => {
    connection.connect(); // reconnect here

Since you're using the default connection method, trying to connect to an already established connection will cause the driver to throw a Handshake error.

If you want to re-use the connection, store it in a variable and then re-use it in other part of your code.

If you want to manage multiple connections instead, I suggest you to look at createPool instead.

Upvotes: 3

Willy wonka
Willy wonka

Reputation: 158

Try removing the connection.connect() and connection.end() from app.get

Upvotes: 0

Related Questions