【问题标题】:How to send error http response in express/node js?如何在 express/node js 中发送错误 http 响应?
【发布时间】:2016-06-22 04:54:17
【问题描述】:

所以在登录页面中,我通过获取请求从角度发送凭据以表达。我想做的是,如果在数据库中找到,发送响应并以角度处理它,如果在数据库中找不到,我想表达发送错误响应并处理它的角度错误响应函数,但我的代码不起作用。

角度控制器:

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

【问题讨论】:

  • 使用res.send("logged err",404);
  • 响应['status_code'] = status_code;响应['消息'] = status_message;响应['error_message'] = error_message;返回 res.jsonp(response);
  • 代码的哪些方面不起作用?您是否收到响应的状态但没有错误消息? $http 承诺的错误处理程序是否无法正常工作。如果您能对问题提供一些清晰的说明,您将很快得到答案。

标签: angularjs node.js express get


【解决方案1】:

在带有 ExpressJS 的 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
        }
    );

【讨论】:

  • 也可以使用json方法javascript req.status(400).json({ message: "This is an invalid request" });
【解决方案2】:

或者使用Error类的实例

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-08-24
    • 2017-10-31
    • 2020-05-22
    • 2020-05-05
    • 1970-01-01
    • 2019-06-23
    • 1970-01-01
    相关资源
    最近更新 更多