如何从 angularjs 中的 POST API 读取位置标头? [英] How to read the Location header from a POST API in angularjs?

查看:20
本文介绍了如何从 angularjs 中的 POST API 读取位置标头?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的post方法是这样的:

 public HttpResponseMessage AddUser(User user){UserManager userManager = new UserManager();尝试{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 }));返回响应;}捕获(异常前){返回 Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex.Message);}}

在 angular 中,我正在尝试读取该位置标题,但到目前为止我仍然无法读取.

return $http.post('http://localhost:30028/api/values/adduser', user).success(功能(数据,状态,标题,配置){警报(angular.toJson(数据));警报(angular.toJson(状态));警报(angular.toJson(标题));警报(angular.toJson(配置));};

我只是在检查每一个的内容,但没有一个有位置标题.有没有一种方法可以通过 angular 访问位置标头,以便我知道新对象的 url?

解决方案

根据文档headers 对象实际上是一个返回头部的函数,就像这样:

.success(function(data, status, headers, config) {警报(标题('位置'));});

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

.success(function(data, status, headers, config) {控制台日志(标题());});

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

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

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

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

<?phpif(isset($_GET['q'])) {header('内容类型:应用程序/json');header('位置:用户/1', true, 200);echo json_encode(array('query' => $_GET['q']));} 别的 {?><!DOCTYPE html><头><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 = "加载中...";$http.get('location.php?q=hello').success(function (data, status, header, config) {控制台日志(标题());$scope.loc = header('位置');}).错误(功能(数据,状态){console.log((data || 'Req Failed') + ': ' + status);});});//]]></script><身体><div ng-app="myApp" ng-controller="myController">位置标题:{{loc}}

</html><?php}

My post method is something like this:

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

    }

In angular, I am trying to read that Location header but so far I'm still not able to.

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

I am just checking out the contents of each of those and none has the location header. Is there a way in angular to access the location header so that i know the url of my new object?

解决方案

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

}

这篇关于如何从 angularjs 中的 POST API 读取位置标头?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆