Halter
Halter

Reputation: 48

How can I read headers sent from my API with angular?

I have something similar to the following code on 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
    });
}

It works great communicating with my .NET API. response.data has all of the data my server needs to give me. However we have a new security token that we are passing to the client from the API and we are passing it in back to the client in the packet header. I know that the token is being passed back because I can read it in the packet on the network tab in chrome debugger. However response.headers() only contains content-type:"application/json; charset=utf-8" It doesn't have what is in the packet. Any one have an idea?

The data is returned from the API like so (C#) HttpContext.Current.Response.AppendHeader("session",Guid.NewGuid().ToString());

So i would expect response to have a header called session, but it does not. It is however in the packet.

Upvotes: 14

Views: 1449

Answers (5)

eGhoul
eGhoul

Reputation: 2590

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

Upvotes: 0

AMRESH PANDEY
AMRESH PANDEY

Reputation: 195

        // 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.

Upvotes: 0

Sachin
Sachin

Reputation: 2922

Use headers method returned in success callback.

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

Do not forget to call headers().

Upvotes: 0

ngCoder
ngCoder

Reputation: 2105

There are two ways of handling $http call i.e .success and .then.But .success is deprecated by Angular since a long time, so it is recommended to use .then.Now to answer the question here is the demo of a simple GET call

$http.get('test.json').then(function(response) {
      $scope.collection = response.data.Collections;
      console.log(response);
      console.log( response.headers());
    });

in this I've set an authentication token to validate the request $http.defaults.headers.common['Auth-Token'] = '1234';,but if I do console.log(response.headers()) it looks like below

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"

This doesn't show the authentication token,but in the response there is also an object called config which also has headers object which contains my authentication token.Try following this pattern,hope this approach gives you a new view on your problem statement.

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

Upvotes: 0

Muhammed Neswine
Muhammed Neswine

Reputation: 2047

Use the headers variable in success and error callbacks

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

Upvotes: 13

Related Questions