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());
});
}
答案 0 :(得分:2)
只需将结果写回来,就像这样。
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.');
});
}
注意,我改变了两种方法的签名。
答案 1 :(得分:2)
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);
});
});
}
答案 2 :(得分:1)
不要使用JSON.stringify(),只返回行。