首页 > 解决方案 > 为什么我的获取顺序会改变程序的工作方式?

问题描述

在进行快速编码分配时,我遇到了一个奇怪的错误。

这是我的代码。让我们称之为“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 将返回 '[]'。有谁知道为什么?

谢谢你的帮助!

标签: javascriptmysqllogic

解决方案


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


推荐阅读