在呼叫$http返回错误消息

Return error message on $http call

本文关键字:错误 消息 返回 http 呼叫      更新时间:2023-09-26

在 Angular 中,我发出了一个$http请求,并希望返回一条错误消息,但不确定如何返回。

在 Express 中,我想在出错时执行以下操作(或类似操作)。

res.send(400, { errors: 'blah' });  

在 Angular 中,我目前有这个:

$http.post('/' ,{}).then(function(res) { }, function(err) {
  console.log(err) // no errors data - only 400 error code
});

如何从 Angular 中访问"错误"(即"等等")?

$http消息提供,成功和错误功能:

$http({method: 'GET', url: '/someUrl'}).
success(function(data, status, headers, config) {
// this callback will be called asynchronously
// when the response is available
}).
error(function(data, status, headers, config) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});

如果出现问题,例如服务器错误或其他http错误,错误功能将被触发,您可以捕获错误。

如果其他内容触发或您必须向用户提供某种反馈,则可以使用成功方法,但将数据作为其他圆顶返回,如下所示:

data {message: 'your message here', success: /*true or false*/, result: /*some data*/ }

然后在成功函数中:

$http({method: 'GET', url: '/someUrl'}).
success(function(data, status, headers, config) {
  if(data.success) {
     // do stuff here
  }
  else {
    // show the error or notification somewhere
  }
}).
error(function(data, status, headers, config) {
  //do stuff if error 400, 500
});
我知道

这是一个老问题,但是..我相信你想要的是:

angular.module('App').factory('MainFactory', function($http) {
  return {
    post: function(something) {
      $http
        .post('/api', something)
        .then(function(result) {
          return result.data;
        }, function(err) {
          throw err.data.message;
        });
    }
  };
});

并且来自一个控制器

angular.module('App').controller('Ctrl', function($scope, MainFactory ) {
    $scope.something_to_send = "something"
    MainFactory
      .post($scope.something_to_send)
      .then(function(result){
        // Do something with result data
       }, function(err) {
        // showError(err);
    });
});