0

I encountered a weird bug when doing a quick coding assignment.

Here is my code. Lets call this 'A'

//Grab all the animals from the database
WebApp.get('/all',(req,res) =>
    {
        const connection = mysql.createConnection({
            host : 'localhost',
            user : 'root',
            password : '1234', //Enter your password here 
            // I found that mySQL 8.0 uses a new default authent plugin whereas 5.7 uses a different one, If you get a ER_NOT_SUPPORTED_AUTH_MODE error from the response, try referring to this post to alter your root password. (https://stackoverflow.com/questions/50373427/node-js-cant-authenticate-to-mysql-8-0)
            database: 'animals'
        });

        const query = "SELECT * FROM animals";
        connection.query(query, (err, rows, fields) => 
        {
            if (err) 
            {
                console.error('error : ' + err.stack);
                res.sendStatus(500);
                return;
            }
            console.log("Fetched animals successfully");
            //console.log(rows); // Use this for error checking to see if a authent problem occurs.
            res.json(rows);
        });
    });

and this 'B'

//Grab a selected animal from the database given a valid Id.
WebApp.get('/:id',(req,res) =>
    {
        console.log("Fetching user with id: " + req.params.id);

        const connection = mysql.createConnection({
            host : 'localhost',
            user : 'root',
            password : '1234', //Enter your password here 
            // I found that mySQL 8.0 uses a new default authent plugin whereas 5.7 uses a different one, If you get a ER_NOT_SUPPORTED_AUTH_MODE error from the response, try referring to this post to alter your root password. (https://stackoverflow.com/questions/50373427/node-js-cant-authenticate-to-mysql-8-0)
            database: 'animals'
        });

        const animalId = req.params.id;
        const query = "SELECT * FROM animals WHERE id = ?";
        connection.query(query, [animalId], (err, rows, fields) => 
        {
            if (err) 
            {
                console.error('error : ' + err.stack);
                res.sendStatus(500);
                return;
            }
            console.log("Fetched animals successfully");
            //console.log(rows); // Use this for error checking to see if a authent problem occurs.
            res.json(rows);
        });
    });

For some reason, if I put A before B it works, and I get successful results from my queries. However, if I put B before A, B will return successfully, but A will return '[]'. Anyone know why?

Thanks for any help!

Caleb Renfroe
  • 183
  • 1
  • 13

1 Answers1

0

Have you tried terminating the connection after each request, or considered using a connection pool? I am not familiar with nodeJS integration with MySQL, but in SQLServer, it is best to use ConnectionPool, when asynchronously making database requests.

JGof
  • 139
  • 5