2016-03-08 128 views
5

所以在登錄頁面我發送憑證從角度來表達通過獲取請求。我想要做的是,如果在數據庫中發現,發送響應和角度處理,否則如果沒有在數據庫中找到我想快遞發送錯誤響應和處理它的角度錯誤響應函數,但我的代碼沒有工作。如何在express/node js中發送錯誤http響應?

角控制器:

myapp.controller('therapist_login_controller', ['$scope' ,'$localStorage','$http', 
    function ($scope, $localStorage,$http) { 


     $scope.login=function(){ 

     console.log($scope.username+$scope.password); 

     var data={ 
      userid:$scope.username, 
      password:$scope.password 
     }; 

     console.log(data); 


      $http.post('/api/therapist-login', data) 
         .then(
          function(response){ 
           // success callback 
           console.log("posted successfully"); 
           $scope.message="Login succesful"; 

          }, 
          function(response){ 
           // failure callback,handle error here 
           $scope.message="Invalid username or password" 
           console.log("error"); 
          } 
         ); 



     } 

    }]); 

APP.js:

app.post('/api/therapist-login',therapist_controller.login); 

控制器:

module.exports.login = function (req,res) { 

     var userid=req.body.userid; 
     var password=req.body.password; 
     console.log(userid+password); 

     Credentials.findOne({ 
      'userid':[userid], 
      'password':[password] 
     },function(err,user){ 
      if(!user){ 
       console.log("logged err"); 
       res.status(404);//Send error response here 
enter code here 
      }else{ 
       console.log("login in"); 

       // 
      } 


     }); 


} 
+1

使用'res.send( 「登錄ERR」,404);' – MiTa

+0

響應[ 'STATUS_CODE'] = STATUS_CODE; response ['message'] = status_message; response ['error_message'] = error_message; return res.jsonp(response); –

+0

代碼的哪個方面不起作用?你是否收到回覆的狀態,但沒有錯誤信息? '$ http'承諾的錯誤處理程序是否失敗。 如果您能夠提供一些清晰的問題,您將很快得到答案。 – gnerkus

回答

8

在節點可以使用res.status()發送錯誤:

return res.status(400).send({ 
    message: 'This is an error!' 
}); 

在角可以抓住它在許響應:

$http.post('/api/therapist-login', data) 
    .then(
     function(response) { 
      // success callback 
      console.log("posted successfully"); 
      $scope.message = "Login succesful"; 

     }, 
     function(response) { 
      // failure callback,handle error here 
      // response.data.message will be "This is an error!" 

      console.log(response.data.message); 

      $scope.message = response.data.message 
     } 
    ); 
+0

非常有幫助,謝謝! –

相關問題