【问题标题】:How can i access the response header in .then function AngularJS我如何访问 .then 函数 AngularJS 中的响应标头
【发布时间】:2017-01-10 12:31:52
【问题描述】:

你知道我如何从 get 请求中访问响应头吗?

我有一个返回承诺的服务功能。我的控制器解决了承诺,并且在 .then 函数中我需要响应标头中的内容类型。

我已经尝试使用“headers”参数,我使用 console.log(headers()) 显示该参数,但控制台中显示错误“headers() is not a function”。

我的服务:

.factory('GetResultFile',
['$http', '$q',
function ($http, $q) {

    var service = {};
    service.getResult = function(id, rid) {

        var deferred = $q.defer();

        $http
        .get('http://localhost:9999/v1/jmeter/' + id + '/results/' + rid, {cache: false})
        .then(function(data, status, headers, config) {
            if(data.status == 200) {
                console.log(data.status);
                deferred.resolve(data);
            }
            else {
                deferred.reject(data);
            }
        });
        return deferred.promise;                
    }
    return service;

}]);

控制器:

$scope.getResult = function(rid) {
        console.log($scope.id);
        GetResultFile.getResult($scope.id, rid)
        .then(function(data, headers) {
            //console.log(headers.Content-type);
            console.log(headers());
            console.log(data);
            console.log("Download succeed");
            console.log(data.status);

            var file = new Blob([data.data], {type: 'text/plain;charset=utf-8'});
            FileSaver.saveAs(file, 'test.txt');

        }, function (data) {
            console.log("Download ERROR!");
            console.log(data.status);
        })
    };              

}])

【问题讨论】:

  • 能否添加您的服务代码。
  • 我更新了我的答案。 @MoshFeu 哦,我会检​​查帖子
  • @kai 检查我的答案并接受它如果它满足你

标签: javascript angularjs header


【解决方案1】:

没有更多信息,我只能考虑标准的东西,例如

    this.$http.get('/your/Route')
      .then(response => {
        console.log(response) // Full information
        console.log(response.data) // holds your Data
        console.log(response.config) // holds more Specific information like the Url and more
        console.log(response.headers());// Specific headers Information
        console.log(response.headers(["content-type"]));//gets the Content-Type of Header

});

一般用于 Angular 服务和响应

响应对象具有以下属性:

  • data{string|Object} – 使用转换函数转换的响应正文。

  • status{number} – 响应的 HTTP 状态代码。

  • headers{function([headerName])} – Header getter 函数。

  • config{Object} – 用于生成请求的配置对象。

  • statusText{string} – 响应的 HTTP 状态文本。

https://docs.angularjs.org/api/ng/service/$http

【讨论】:

  • 嗨,谢谢你的回答。一个问题:如何从响应标头中检查内容类型? console.log(headers([content-type]) ?
  • @Kai 是的,只要 console.log(response.headers(["content-type"]));。将使用该解决方案编辑我的答案
  • 谢谢你,我已经用 console.log(response.header('content-type')) 试试了!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-02-14
  • 2023-03-06
  • 2012-02-24
  • 1970-01-01
  • 2020-12-13
相关资源
最近更新 更多