node json请求堆栈

Hus*_*Ali 1 javascript node.js

大家好我知道我的问题很容易买我是新的使用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;
Run Code Online (Sandbox Code Playgroud)

结果是

[ RowDataPacket { countryId: 1, countryName: 'N/A' },
  RowDataPacket { countryId: 2, countryName: 'UK' },
  RowDataPacket { countryId: 3, countryName: 'USA' },
  RowDataPacket { countryId: 4, countryName: 'UAE' } ]
Run Code Online (Sandbox Code Playgroud)

我希望响应如此

  { countryId: 1, countryName: 'N/A' },
  { countryId: 2, countryName: 'UK' },
  { countryId: 3, countryName: 'USA' },
  { countryId: 4, countryName: 'UAE' } 
Run Code Online (Sandbox Code Playgroud)

使用RowDataPacket并将其重新发送到ejs视图

ade*_*neo 5

[ 
  RowDataPacket { countryId: 1, countryName: 'N/A' },
  RowDataPacket { countryId: 2, countryName: 'UK'  },
  RowDataPacket { countryId: 3, countryName: 'USA' },
  RowDataPacket { countryId: 4, countryName: 'UAE' } 
]
Run Code Online (Sandbox Code Playgroud)

这就是控制台显示结果的方式,因为从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);
    }
});
Run Code Online (Sandbox Code Playgroud)