Подтвердить что ты не робот

Как отправить сообщение об ошибке HTTP в express/node js?

Итак, на странице входа в систему я отправляю учетные данные из angular, чтобы выразить через запрос get. Что я хочу сделать, так это если я нашел в базе данных, отправить ответ и обработать его в angular, если не найден в db, я хочу, чтобы express отправил ответ об ошибке и обработал функция ответа угловой ошибки, но мой код не работает.

Угловой контроллер:

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");
      }
    });
  }
4b9b3361

Ответ 1

В Node вы можете использовать res.status() для отправки ошибки:

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

В Angular вы можете поймать его в ответе на обещание:

$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
        }
    );

Ответ 2

Или используйте экземпляр класса Error

response.status(code).send(new Error('description'));