2016-12-27 50 views
1

我寫這條路線查找用戶每次我進入錯誤的用戶我沒有得到res.json()味精貓鼬:爲什麼我沒有收到錯誤響應

app.post('/authenticate', function(req, res){ 

    user.findOne({email : req.body.username}, function(err, user){ 
      if(err){ 
      res.json('user not found'); //not getting this 
      }else{ 
      console.log(user); //probably this ran, cuz getting null at cmd 
      } 
    }) 
}) 

回答

1

當用戶名沒有按」與任何文檔匹配,它將返回空用戶json。誤差err對象是空,因此res.json不可達,所以你必須通過

app.post('/authenticate', function(req, res){ 

     user.findOne({email : req.body.username}, function(err, user){ 
       if(err){ 
       throw err; 
       }else{ 
       if(user){ 
        console.log(user); //probably this ran, cuz getting null at cmd 
       }else{ 
        console.log("User Not Found"); 
       } 

       } 
     }) 
    }) 
+0

來處理這個那麼爲什麼會出現回調ERR參數,如果沒有得到任何東西,如果文檔didnt匹配 –

+0

犯錯是檢查錯誤發生在查詢時,如果沒有發生錯誤,它將爲空@johndoe – Sumeet

+0

你能解釋api如何適用於'/ api',爲什麼它以這種方式寫api中間件,路由器https://scotch.io/tutorials/authenticate-a- node-js-api-with-json-web-tokens :) –

相關問題