我试图返回一个 JSON 对象,但它返回一个数组。我使用主键进行查询,因此我确信我只会得到一个结果。
这是我的方法:
router.get("/student_info/:id", (req, res, next) => {
connection.getConnection((error, currentConnection) => {
if (!!error) {
console.log("Error occurred while connecting db")
} else {
let id = req.params.id;
currentConnection.query("SELECT * FROM students WHERE id=" + "'" + id + "'", (error, rows, fields) => {
if (!!error) {
console.log(error.message)
} else {
res.status(200).json(rows);
}
currentConnection.release();
});
}
});
});
我想要的是这样的:
{
"id": "171-15-8966",
"name": "Alif Hasnain",
"course_code": "CSE412,CSE413"
}
但我得到的结果是这样的:
[
{
"id": "171-15-8966",
"name": "Alif Hasnain",
"course_code": "CSE412,CSE413"
}
]
最佳答案
只需在 json 转换之前获取数组的第一个元素即可:
res.status(200).json(rows[0]);
关于javascript - 如何返回一个对象而不是数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60740386/