nodejs mysql查询select语句的返回值

module.exports.getTragos = function(req, res) { var connection = conectar(); connection.connect(); connection.query('SELECT * from tipoAlcohol', function(err, rows, fields) { if (!err) return JSON.stringify(rows)); else return 'Error while performing Query.'; }); connection.end(); } 

我想使getTragos函数返回执行查询的行,但return JSON.stringify(rows)); 没有返回他们。 我试图把console.log(rows)和查询执行正常。

这是调用getTragos的代码:

 module.exports.iniciar = function(app) { app.get('/bebidas/getTipoAlcohol', function (req, res) { res.send(modelo.getTragos()); }); } 

就这样写下结果来回应。

 module.exports.iniciar = function(app) { app.get('/bebidas/getTipoAlcohol', function(req, res, next) { modelo.getTragos(function(err, tragos) { if(err) {return next(err);} //do you processing here // then write the result to the response var result = doSomething(tragos); // i am assuming that doSomething is synchronous. res.json(result); }); }); } module.exports.getTragos = function(callback) { var connection = conectar(); connection.connect(); connection.query('SELECT * from tipoAlcohol', function(err, rows, fields) { connection.end(); if (!err) return callback(null, rows); else return callback('Error while performing Query.'); }); } 

注意,我改变了这两种方法的签名。

 module.exports.getTragos = function(req, res, callback) { var connection = conectar(); connection.connect(); connection.query('SELECT * from tipoAlcohol', function(err, rows, fields) { if (!err) callback(rows); else return 'Error while performing Query.'; }); connection.end(); } module.exports.iniciar = function(app) { app.get('/bebidas/getTipoAlcohol', function (req, res) { modelo.getTragos(req, res, function(returnedValue){ res.send(returnedValue); }); }); } 

不要使用JSON.stringify(),只返回行。