2016-03-08 18 views
5

ログインページで私は角度から証明書を送っています。私がしたいのは、データベースに見つかったら、応答を送信し、dbで見つからない場合は角度で処理します。エラー応答を送信したいと思います。角度エラー応答関数を処理しますが、私のコードは動作しません。エクスプレス/ノード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(、404 "ERRをログに記録");' – MiTa

+0

応答[ 'STATUS_CODE'] = STATUS_CODE。 レスポンス['message'] = status_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

非常に参考になりました、ありがとう! –

関連する問題