[英]RestFul API Node.js, Express - error status - response empty array
我正在 Node.JS 中創建一個 RestFull API,用於檢查特定車牌是否已在數據庫 (MySQL) 中注冊,最后我只通知 Ex board: (http://localhost:3009/_api_v1/car/ ABC2012 ) 並使用 get 函數,如果此卡存在,它將以 json 格式返回此卡,直到它工作為止,但如果您輸入未注冊的卡,例如 (http://localhost:3009/_api_v1/car/WWW3432 )) 應該返回一個消息 err.status (Error ('404 Not Found'),但它返回一個空數組 [] 並且沒有這個消息
router.get('/:id?', function (req, res, next){
Node.getNodeBylicensePlate(req.params.id,function(err,rows){
if(err)
{
res.json(err);
}
else
{
res.json(rows);
}
});
});
============================
getNodeBylicensePlate:function(licensePlate,callback){
return db.query("select licensePlate from car where licensePlate=?",[licensePlate],callback);
},
我假設這是因為如果存在真正的 Sql 錯誤(無效查詢、超時、死鎖等),您只會返回錯誤。
您需要詢問rows
變量,如果空結果返回 404:
router.get('/:id?', function (req, res, next){
Node.getNodeBylicensePlate(req.params.id,function(err,rows){
if(err)
{
res.json(err);
}
else
{
if (!rows || !rows.length) {
res.status(404);
}
else {
res.json(rows);
}
}
});
});
我猜 mysql 查詢返回一個空數組
router.get('/:id?', function (req, res, next){
Node.getNodeBylicensePlate(req.params.id,function(err,rows){
if(err) {
res.json(err);
return;
}
if (!rows.length) {
res.status(404).send({ message: 'Not Found' });
return;
}
res.json(rows);
});
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.