Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/mysql/62.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Mysql ExpressJS-发送变量作为POST请求的响应_Mysql_Sql_Node.js_Express - Fatal编程技术网

Mysql ExpressJS-发送变量作为POST请求的响应

Mysql ExpressJS-发送变量作为POST请求的响应,mysql,sql,node.js,express,Mysql,Sql,Node.js,Express,我正在尝试检索SQL的插入ID并将其发送回前端。但是当我执行res.send(result.insertId)时,我得到一个500错误。如何将sql的插入ID成功地传递到前端 router.post('/list', function(req, res, next) { var lastIncrement = 0; pool.getConnection(function (error, connection) { connection.query('INSERT

我正在尝试检索SQL的插入ID并将其发送回前端。但是当我执行res.send(result.insertId)时,我得到一个500错误。如何将sql的插入ID成功地传递到前端

router.post('/list', function(req, res, next) {
    var lastIncrement = 0;
    pool.getConnection(function (error, connection) {
        connection.query('INSERT INTO test_table SET Name = ?, Age = ?', [req.body.Name, req.body.Age], function (error, result) {
            if(error)
                console.error(error);
            lastIncrement = result.insertId;
            connection.release();
        });
    });
    res.send(lastIncrement);
});

您的代码中有一个问题,确保在完成查询之前返回。因此,您必须从回调函数内部返回

router.post('/list', function(req, res, next) {
var lastIncrement = 0;
pool.getConnection(function (error, connection) {
    connection.query('INSERT INTO test_table SET Name = ?, Age = ?', [req.body.Name, req.body.Age], function (error, result) {
        if(error)
            console.error(error);
        lastIncrement = result.insertId;
        connection.release();
        res.send(lastIncrement);
    });
});

});

由于nodejs的异步特性,res.send在查询返回值之前执行。您可以使用
。然后
承诺确保
res.send
在您从查询中获取值后发生,或者在分配值后使用
res.send

您可以尝试以下方法:

pool.getConnection(function (error, connection) {
    connection.query('INSERT INTO test_table SET Name = ?, Age = ?', [req.body.Name, req.body.Age], function (error, result) {
        if(error)
            console.error(error);
        lastIncrement = result.insertId;
        connection.release();
    }).then(function(){
        res.send(lastIncrement);
    })
});