如何从angularjs中的POST API读取Location标头?

rab*_*ana 10 post http-headers 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);
        }

    }
Run Code Online (Sandbox Code Playgroud)

在角度,我试图读取位置标题,但到目前为止,我仍然无法.

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));
         };
Run Code Online (Sandbox Code Playgroud)

我只是检查每个的内容,没有没有位置标题.是否有角度访问位置标题,以便我知道我的新对象的网址?

Ove*_*ous 20

根据文档,该headers对象实际上是一个返回标头的函数,如下所示:

.success(function(data, status, headers, config) {
    alert( headers('Location') );
});
Run Code Online (Sandbox Code Playgroud)

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

.success(function(data, status, headers, config) {
    console.log( headers() );
});
Run Code Online (Sandbox Code Playgroud)

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

因此,请确保您正确设置响应代码.我在PHP中测试它(我没有那么多使用),并且忘记了设置Location标题会自动设置响应代码.为了测试这个,我不得不使用:

header('Location: blah-blah', true, 200);
Run Code Online (Sandbox Code Playgroud)

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

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

}
Run Code Online (Sandbox Code Playgroud)