【问题标题】:Catch status 500 in AngularJS from API REST从 API REST 在 AngularJS 中捕获状态 500
【发布时间】:2015-12-23 04:41:43
【问题描述】:

我有一个 Angular 应用程序,它使用 Node JS 中的 API REST 创建,问题是我不确定向客户端传达错误的最佳形式,我想这是发送状态为 500 的消息,但在这种情况下如何在 Angular 中传递这条消息?

例如我在Node中有以下方法

router.post('/create', function(req, res, next) {
  models.form.create(req.body

  ).then(function(form) {
    res.send(form.dataValues)  
  }).catch(function(error) {
    console.log (error);
    res.status(500).send(error);
  });
});

这是在 Angular 中使用的服务来消费

createForm : function (form) {
    var auxResource = $resource(localPath + 'create');
    return new auxResource(form).$save()
         .then(function (formCreated) { 
            console.log(formCreated);
            formCreate = formCreated;
         })

},

控制器方法

this.create = function create () {
    formRESTService.create($scope.form)
         .then(function () {  
               $location.path("/formList");             
          })
           .catch(function (error) {
              console.log("entre al cath");
              console.log("ENTREEEEE" + error);
          });
}

问题是 Angular 从来没有发现错误,我该怎么做?

【问题讨论】:

    标签: angularjs node.js api


    【解决方案1】:

    我认为有一个简单的原因。

    您正在使用.then() 回调。不,如果你查看$resource 的文档,你会看到,这个回调有两个函数:

    .then(function(data) {...}, function(error) {...});

    500 错误通常被困在错误回调中。

    如果您在成功回调中不期待正文并且您省略了成功回调,则只能使用 .catch(...)

    请参阅https://docs.angularjs.org/api/ng/service/$q,您可以在其中找到有关 Promise API 的完整文档。

    【讨论】:

      猜你喜欢
      • 2013-10-09
      • 1970-01-01
      • 2012-12-24
      • 2018-09-08
      • 1970-01-01
      • 2017-04-26
      • 1970-01-01
      • 1970-01-01
      • 2023-04-04
      相关资源
      最近更新 更多