【问题标题】:How to read the Location header from a POST API in angularjs?如何从 angularjs 中的 POST API 读取 Location 标头?
【发布时间】:2013-07-27 20:14:31
【问题描述】:

我的 post 方法是这样的:

    public HttpResponseMessage AddUser(User user)
    {
        UserManager userManager = new UserManager();
        try
        {
            userManager.Create(user);

            var savedUser = userManager.FindUserByClientId(user.ClientId);
            HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.Created, user);
            response.Headers.Location = new Uri(Url.Link("DefaultApi", new { id = savedUser.Id }));
            return response;
        }
        catch(Exception ex)
        {
            return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex.Message);
        }

    }

在 Angular 中,我正在尝试读取 Location 标头,但到目前为止我仍然无法读取。

return $http.post('http://localhost:30028/api/values/adduser', user)
        .success(function (data, status, headers, config) {
            alert(angular.toJson(data));
            alert(angular.toJson(status));
            alert(angular.toJson(headers));
            alert(angular.toJson(config));
         };

我只是检查每个内容的内容,没有一个有位置标题。有没有一种角度访问位置标头的方法,以便我知道我的新对象的 url?

【问题讨论】:

    标签: post angularjs http-headers


    【解决方案1】:

    According to the documentationheaders对象其实是一个返回头部的函数,像这样:

    .success(function(data, status, headers, config) {
        alert( headers('Location') );
    });
    

    如果你想要一个所有标题的集合,你可以这样做:

    .success(function(data, status, headers, config) {
        console.log( headers() );
    });
    

    注意:如果您的服务器设置了301302 的响应代码,您将无法获取Location 标头,因为它将自动和透明地跟随 XMLHttpRequest 对象。

    因此,请确保您正确设置了响应代码。我在 PHP 中对此进行了测试(我使用得不多),并且忘记了设置 Location 标头会自动设置响应代码。为了测试这一点,我不得不使用:

    header('Location: blah-blah', true, 200);
    

    这是我的工作代码示例,只需将其保存到 PHP 服务器上的 location-test.php 并运行它:

    <?php
    
    if(isset($_GET['q'])) {
        header('Content-Type: application/json');
        header('Location: user/1', true, 200);
        echo json_encode(array('query' => $_GET['q']));
    } else {
    
    ?>
    <!DOCTYPE html>
    <html>
    <head>
      <meta http-equiv="content-type" content="text/html; charset=UTF-8">
    
      <script type='text/javascript' src='//cdnjs.cloudflare.com/ajax/libs/angular.js/1.1.5/angular.min.js'></script>
      <script type='text/javascript'>//<![CDATA[ 
    
    angular.module('myApp', [])
    .controller("myController", function($scope, $http) {
        $scope.loc = "Loading...";
        $http.get('location.php?q=hello')
            .success(function (data, status, header, config) {
                console.log(header());
                $scope.loc = header('Location');
             })
            .error(function(data, status) {
                console.log((data || 'Req Failed') + ': ' + status);
            });
    });
      //]]></script>
    
    </head>
    <body>
        <div ng-app="myApp" ng-controller="myController">
            Location Header: {{loc}}
        </div>
    </body>
    </html>
    
    <?php
    
    }
    

    【讨论】:

    【解决方案2】:

    由于 .success() 在 $http 中已弃用并已替换为 .then(),因此对此答案的更新是直接在注入承诺的响应上调用 header

    $http.post('http://localhost:30028/api/values/adduser', user)
        .then(function (response) {
            alert(angular.toJson(response.headers));
            //or
            alert(response.headers('Location'));
     });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-12-25
      • 1970-01-01
      • 1970-01-01
      • 2013-12-14
      • 2016-07-31
      • 2016-09-02
      • 2015-11-29
      • 1970-01-01
      相关资源
      最近更新 更多