2013-07-27 13 views
10

Moja metoda post jest coś takiego:Jak odczytać nagłówek Location z POST API w angularjs?

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); 
     } 

    } 

W kątowe, staram się czytać tego nagłówka Location ale jak dotąd nadal nie jestem w stanie.

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)); 
     }; 

Właśnie sprawdzam zawartość każdego z nich i żaden nie ma nagłówka lokalizacji. Czy istnieje kąt w dostępie do nagłówka lokalizacji, tak że znam adres URL mojego nowego obiektu?

Odpowiedz

18

According to the documentation, obiekt headers faktycznie jest funkcja, która zwraca nagłówek, tak:

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

Jeśli chcesz kolekcję wszystkich nagłówków, można to zrobić:

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

Uwaga: Jeśli twój serwer ustawi kod odpowiedzi na 301 lub 302, będziesz nie w stanie aby uzyskać nagłówek Location, ponieważ będzie on automatycznie i przezroczysty, po którym następuje obiekt XMLHttpRequest.

Upewnij się, że poprawnie ustawiłeś kod odpowiedzi. Testowałem to w PHP (którego nie używam tak dużo) i zapomniałem, że ustawienie nagłówka Location automatycznie ustawia kod odpowiedzi. Aby to sprawdzić, musiałem użyć:

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

Oto mój przykładowy kod pracy, wystarczy zapisać go do location-test.php na serwerze PHP i uruchomić go:

<?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

Czy to nie łamie HTTP? Lokalizacja nie powinna iść z 200. –

+0

@ MikaelÖstberg to dobrze z 202s. http://farazdagi.com/blog/2014/rest-long-running-jobs/ –

1

Od .success() jest przestarzałe w $ http i został zastąpiony przez .then() aktualizacją tej odpowiedzi jest wywołanie header bezpośrednio na odpowiedź, która jest wstrzykiwana w obietnicę.

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