How to read the Location header from a POST API in angularjs?

后端 未结 2 1943
既然无缘
既然无缘 2020-12-19 01:12

My post method is something like this:

    public HttpResponseMessage AddUser(User user)
    {
        UserManager userManager = new UserManager();
        t         


        
相关标签:
2条回答
  • 2020-12-19 02:06

    Since .success() is deprecated in $http and has been replaced with .then() the update to this answer is to call header directly on the response that is injected into the promise.

    $http.post('http://localhost:30028/api/values/adduser', user)
        .then(function (response) {
            alert(angular.toJson(response.headers));
            //or
            alert(response.headers('Location'));
     });
    
    0 讨论(0)
  • 2020-12-19 02:14

    According to the documentation, the headers object is actually a function that returns the header, like so:

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

    If you want a collection of all headers, you can do this:

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

    Note: If your server sets a response code of 301 or 302, you will not be able to get the Location header, as it will be automatically and transparently followed by the XMLHttpRequest object.

    So, make sure you are correctly setting the response code. I was testing this in PHP (which I don't use as much), and had forgotten that setting a Location header automatically set the response code. To test this, I had to use:

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

    Here's my working code sample, just save it to location-test.php on a PHP server and run it:

    <?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
    
    }
    
    0 讨论(0)
提交回复
热议问题