大家好,我知道我的问题很简单,我是 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 View
最佳答案
[
RowDataPacket { countryId: 1, countryName: 'N/A' },
RowDataPacket { countryId: 2, countryName: 'UK' },
RowDataPacket { countryId: 3, countryName: 'USA' },
RowDataPacket { countryId: 4, countryName: 'UAE' }
]
这是控制台显示结果的方式,因为从 MySQL 返回的数据是 RowDataPacket
类型,但您实际得到的只是您想要的对象,您不必做任何事。
如果你真的想摆脱类型,你可以这样做
con.query(sql, function(err, rows) {
if (err) {
throw err
} else {
var str = JSON.stringify(rows);
rows = JSON.parse(str);
console.log(rows);
}
});
关于javascript - Node json请求栈,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34839447/