提问者:小点点

为什么my get的顺序会改变程序的工作方式?


我在做快速编码任务时遇到了一个奇怪的bug。

这是我的代码。让我们称之为“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);
        });
    });

还有这个'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);
        });
    });

出于某种原因,如果我把A放在B之前,它是有效的,我从查询中得到成功的结果。然而,如果我把B放在A之前,B会成功返回,但是A会返回 '[]'. 有人知道为什么吗?

感谢任何帮助!


共1个答案

匿名用户

您是否尝试过在每次请求后终止连接,或者考虑使用连接池?我不熟悉nodeJS与MySQL的集成,但在SQLServer中,最好使用ConnectionPool,当异步发出数据库请求时。