0

我在 AngularJS 中有一个 $http POST 调用,如果请求错误,它不会显示服务器响应。

myFactory.create = function(formData) {
  deferred = $q.defer()
  $http({method: 'POST', url: url, responseType: 'json', data: formData})
    .then(function(data) {
      deferred.resolve(data);
    }, function(response, status, headers, config) {
      deferred.reject(response);
  });

  return deferred.promise;
};

当我提交不正确的数据时,API 会以 400 - Bad Request 响应。如果我查看 Chrome 开发者工具中的响应,会有一条纯文本消息:“垂直不正确。” 但是,该消息不在 $http 错误回调的响应中。

我可以获得其他所有内容(状态、标题和配置),但我的响应数据为空。

成功的 POST 被正确处理,所以我知道该功能通常有效。

知道为什么我可以在 Chrome 中看到响应但无法通过 $http 访问它吗?

4

1 回答 1

0

您可以对此进行重构:

myFactory.create = function(formData) {
  var url = 'api/create';  
  return $http({
    method: 'POST', 
    url: url, 
    responseType: 'json',  //Are you sure that it is returning a json??
    data: formData
  });
};

然后在任何你想调用它的地方检查这样的承诺的回报,

myFactory.create().then(
  function(data){
     console.dir(data);
  },function(response, status, headers, config) {
     console.dir(response);
  });

这应该可以工作,您应该会在日志中看到数据。

于 2015-01-09T21:56:57.123 回答