我怎么能读取头从我的API发送与angular

本文关键字:angular API 我的 怎么能 读取 | 更新日期: 2023-09-27 18:06:58

我在domain.com上有类似以下代码:

$http.post("http://api.domain.com/Controller/Method",
    JSON.stringify(data),
    {
        headers: {
            'Content-Type': 'application/json'
        }
    })
    .then(function (response) {
        console.log(response);
    }, function (response) {
        // something went wrong
    });
}

它可以很好地与我的。net API通信。response.data有我的服务器需要给我的所有数据。然而,我们有一个新的安全令牌,我们正在从API传递给客户端,并在数据包头中将其传递回客户端。我知道令牌正在被传递回来,因为我可以在chrome调试器的网络选项卡上的数据包中读取它。然而response.headers()只包含content-type:"application/json; charset=utf-8",它没有包里的东西。有人知道吗?

数据像这样从API返回(c#)HttpContext.Current.Response.AppendHeader("session",Guid.NewGuid().ToString());

所以我希望response有一个标题称为session,但它没有。

我怎么能读取头从我的API发送与angular

在成功和错误回调中使用headers变量

$http.get('/url').
  success(function(data, status, headers, config) {
    //things to do
  })
  .error(function(data, status, headers, config) {
    //things to do
  });

有两种方法可以处理$http调用,即.success.then,但是.success早就被Angular弃用了,所以建议使用.then。现在来回答这个问题,这里是一个简单的GET调用的演示

$http.get('test.json').then(function(response) {
      $scope.collection = response.data.Collections;
      console.log(response);
      console.log( response.headers());
    });
在这里,我设置了一个身份验证令牌来验证请求$http.defaults.headers.common['Auth-Token'] = '1234';,但如果我做console.log(response.headers()),它看起来像下面
cache-control   :    "no-cache"
cf-ray    :    "2e3a4163cdf43084-SIN"
content-encoding   :    "gzip"
content-type    :    "application/json; charset=utf-8"
date    :    "Sat, 17 Sep 2016 05:46:02 GMT"
etag    :    ""1ae47a56e2b2ea9ddc982cc0e61e469a-static-gzip""
server    :    "cloudflare-nginx"
status    :    "304"
vary    :    "accept-encoding"
x-xss-protection    :    "0"

这没有显示身份验证令牌,但在响应中还有一个名为config的对象,它也有包含我的身份验证令牌的headers对象。试着遵循这个模式,希望这个方法能让你对问题陈述有一个新的看法。

config : Object
       L->  headers: Object
             L->     Accept : "application/json, text/plain, */*"
                     Auth-Token : "1234"

使用成功回调时返回的headers方法

$http.get('/url').
  success(function(data, status, headers, config) {
    response.headers = headers();
    console.log(response.headers, response.headers['auth_token']);
  })
  .error(function(data, status, headers, config) {
    //things to do
  });

不要忘记调用headers()

        // Simple GET request example:
$http({
  method: 'GET',
  url: '/someUrl'
}).then(function successCallback(response) {
    // this callback will be called asynchronously
    // when the response is available
  }, function errorCallback(response) {
    // called asynchronously if an error occurs
    // or server returns response with an error status.
  });

    The response object has these properties:
    data – {string|Object} – The response body transformed with the transform functions.
    status – {number} – HTTP status code of the response.
    headers – {function([headerName])} – Header getter function.
    config – {Object} – The configuration object that was used to generate the request.
    statusText – {string} – HTTP status text of the response.
    A response status code between 200 and 299 is considered a success status and will result in the success callback being called. Any response status code outside of that range is considered an error status and will result in the error callback being called. Also, status codes less than -1 are normalized to zero. -1 usually means the request was aborted, e.g. using a config.timeout. Note that if the response is a redirect, XMLHttpRequest will transparently follow it, meaning that the outcome (success or error) will be determined by the final response status code.
$http.post("http://api.domain.com/Controller/Method",
    JSON.stringify(data),
    {
        headers: {
            'Content-Type': 'application/json'
        }
    })
    .then(function (response) {
        console.log(response);
        //this will get you session header information
        console.log( response.headers('session'));
    }, function (response) {
        // something went wrong
    });
}