【问题标题】:Why does the order of my gets change how the program works?为什么我的获取顺序会改变程序的工作方式?
【发布时间】:2020-04-22 23:51:17
【问题描述】:

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

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

感谢您的帮助!

【问题讨论】:

    标签: javascript mysql logic


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-08-18
      • 2018-06-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-05-25
      • 1970-01-01
      相关资源
      最近更新 更多