我正在用 express 和 sqlite 構建一個簡單的 API。我希望我的 GET 請求僅顯示回應中顯示的每個 JSON 物件中的某些鍵。
以下是我當前的代碼:
router.get('/cars', (req, res) => {
// TODO GET all cars
try {
let sql = 'SELECT * FROM cars'
let params = []
db.all(sql, params, (err, rows) => {
if (err) {
res.status(400).json({"error":err.message});
return;
}
else {
res.status(200).json({
message: 'success',
data: rows
})
}
});
} catch(error) {
console.log(error.message.red)
res.status(500).json({
message: 'Not found.'
})
}
})
現在,回應將顯示來自資料庫的條目以及所有鍵及其值。它看起來像這樣:
{
"message": "success",
"data": [
[
{
"car_id": 48,
"email": "[email protected]",
"name": "Hernando",
"year": 2015,
"make": "Acura",
"model": "TLX",
"racer_turbo": 0,
"racer_supercharged": 0,
"racer_performance": 2,
"racer_horsepower": 2,
"car_overall": 4,
"engine_modifications": 4,
"engine_performance": 0,
"engine_chrome": 2,
"engine_detailing": 4,
"engine_cleanliness": 4,
"body_frame_undercarriage": 2,
"body_frame_suspension": 4,
"body_frame_chrome": 2,
"body_frame_detailing": 2,
"body_frame_cleanliness": 2,
"mods_paint": 2,
"mods_body": 2,
"mods_wrap": 0,
"mods_rims": 4,
"mods_interior": 4,
"mods_other": 4,
"mods_ice": 6,
"mods_aftermarket": 2,
"mods_wip": 0,
"mods_overall": "4",
"score": 62
},
...
我只想顯示 car_id、email、name、year、make、model 和 score 鍵及其值,并省略其余鍵。
我試過像這樣使用forEach回圈
if(err) {
res.status(400).json({'error':err.message});
return;
} else {
res.json({
message:'success',
data: rows.forEach((row) => {
row.car_id,
row.email,
row.name,
row.year,
row.make,
row.model,
row.score
}
})
}
但它沒有顯示資料,但我的控制臺也沒有出現任何錯誤。
預期的輸出是這樣的:
"message": "success",
"data": [
[
{
"car_id": 48,
"email": "[email protected]",
"name": "Hernando",
"year": 2015,
"make": "Acura",
"model": "TLX",
"score": 62
},
...
非常感謝任何幫助。
uj5u.com熱心網友回復:
試試這個
let sql = 'SELECT car_id,email,name,year,make,model,score FROM cars'
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/470343.html
上一篇:查詢連接表時有沒有辦法回傳空值行
下一篇:Railsdb:種子如何繞過驗證
