programing

express/node js에서 오류 http 응답을 보내는 방법

nicegoodjob 2023. 3. 25. 13:20
반응형

express/node js에서 오류 http 응답을 보내는 방법

그래서 로그인 페이지에서 get request를 통해 angular에서 express로 credential을 보냅니다.제가 원하는 것은 데이터베이스에서 찾으면 응답을 보내고 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");
      }
    });
  }

Express를 사용하는 노드 내사용할 수 있는 JSres.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
        }
    );

또는 의 인스턴스를 사용합니다.Error학급

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

언급URL : https://stackoverflow.com/questions/35864088/how-to-send-error-http-response-in-express-node-js

반응형