【问题标题】:$http - Headers not returning - AngularJS$http - 标题不返回 - AngularJS
【发布时间】:2017-05-16 03:59:53
【问题描述】:

我有一个 Angular 服务,我正在尝试设置以从节点服务器检索数据,该节点服务器向应用程序提供 JSON 文件。我已经检查了节点服务器 URL,它们都按照应有的方式输出 JSON,但是由于 HTTP 标头,Angular 似乎无法获取它们。从一些谷歌搜索来看,这似乎是一个常见问题,我只是不确定如何解决,甚至是否有解决方法?

eventsApp.factory('eventData', function($http, $log) {
    return {
        getEvent: function(successcb) {
            $http({method: 'GET', url: 'http://localhost:8000/data/event/1'}).
                success(function(data, status, headers, config){
                    successcb(data);
                }).
                catch(function(data, status, headers, config){
                    $log.warn(data, status, headers, config);
                })
        }
    }
});

在控制台中,我收到以下警告:

Object { data: null, status: 0, headers: headersGetter/

【问题讨论】:

  • 您应该使用.then() 而不是.success(),因为.success() 已被弃用。 .then() 有一个 response 参数,您应该可以从中访问标头。
  • 我对 Angular 完全陌生(这周才开始学习),所以对我来说很简单,但是除了用 then 替换成功之外,这将如何改变上面的代码?
  • 使用控制台中错误的屏幕截图更新您的帖子,以提供更多详细信息
  • 不要将回调与 promise API 一起使用。他们打破了承诺链并挂在错误条件上。见Why are Callbacks from Promise Then Methods an Anti-Pattern?
  • 状态 0 表示可能存在 CORS 问题。

标签: javascript angularjs json node.js


【解决方案1】:

来自documentation

// Simple GET request example:
$http({
  method: 'GET',
  url: '/someUrl'
}).then(function successCallback(response) {
    // this callback will be called asynchronously
    // when the response is available
  }, function errorCallback(response) {
    // called asynchronously if an error occurs
    // or server returns response with an error status.
  });

响应对象具有以下属性:

  • data – {string|Object} – 响应体转换为 变换函数。
  • status – {number} – HTTP 状态码 回应。
  • headers – {function([headerName])} – Header getter 函数。
  • config - {Object} - 用于生成的配置对象 请求。
  • statusText – {string} – 响应的 HTTP 状态文本。

所以你应该能够使用以下方法获取感兴趣的标题:

response.headers('header-name')

根据您的回复日志,result.data 为空。因此,您应该检查Chrome Dev ToolsNetwork 选项卡并检查来自服务器的aqtual http 响应。

status 0 表示可能的CORS 问题。因此,如果您的 Angular 应用程序托管在另一个主机或端口上,而不是您尝试向其发送 http 请求的服务器(在您的情况下为 localhost:8000),那么您应该配置 SERVER 以允许 CORS 请求。

【讨论】:

  • 好的,我已将其更改为 then(function successCallback(response){ successcb(response.data); }),但仍然失败
  • 所以,按照我的建议去做:在 Chrome 的开发工具中检查真实的 http 响应。 data 为空,status==0 表示您的请求甚至没有传递到服务器。如果您的 Angular 应用程序托管在与您发送 http 请求的服务器 (localhost:8000) 不同的 host:port 上,则可能是 CORS 问题。
  • Status 是 200 加上在直接将 url 输入浏览器时加载没有问题,这肯定意味着它没问题?
  • 然后我几乎可以肯定这是CORS问题。但是您应该在 Chrome 开发工具 console 标签中看到这一点。
猜你喜欢
  • 1970-01-01
  • 2018-01-09
  • 2023-03-23
  • 2013-10-21
  • 1970-01-01
  • 2015-04-19
  • 2014-07-30
  • 2015-01-12
  • 1970-01-01
相关资源
最近更新 更多