节点json请求堆栈

大家好,我知道我的问题是很容易购买我新使用json。

var mysql = require('mysql'); function myCon(sql){ var con = mysql.createConnection({ host: "127.0.0.1", port: "3306", user: "root", password: "xxxxxx", database: "myDataBase", }); // here i'm passing sql query as var sql con.query(sql, function(err, rows) { if (err) { throw err } else { console.log(rows); // here I want my response to be json response eg { key:value} } }) con.end(); } module.exports.con = myCon; 

结果是

 [ RowDataPacket { countryId: 1, countryName: 'N/A' }, RowDataPacket { countryId: 2, countryName: 'UK' }, RowDataPacket { countryId: 3, countryName: 'USA' }, RowDataPacket { countryId: 4, countryName: 'UAE' } ] 

我想要的答复是

  { countryId: 1, countryName: 'N/A' }, { countryId: 2, countryName: 'UK' }, { countryId: 3, countryName: 'USA' }, { countryId: 4, countryName: 'UAE' } 

出RowDataPacket并重新发送到ejs视图

 [ RowDataPacket { countryId: 1, countryName: 'N/A' }, RowDataPacket { countryId: 2, countryName: 'UK' }, RowDataPacket { countryId: 3, countryName: 'USA' }, RowDataPacket { countryId: 4, countryName: 'UAE' } ] 

这就是控制台显示结果的方式,因为从MySQL返回的数据是RowDataPackettypes的,但是实际上你得到的只是你想要的对象,你不需要做任何事情。

如果你真的想摆脱的types,你可以做

 con.query(sql, function(err, rows) { if (err) { throw err } else { var str = JSON.stringify(rows); rows = JSON.parse(str); console.log(rows); } });