Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get own headers $Resource AngularJs

Tags:

rest

angularjs

I have a REST API in GO language and the front-end in Angularjs , but when I get my resource in angular my custom header don't exist.

Controller:

  Persons.query(
    function (data, headerGetter, status) {

      var headers = headerGetter();

      console.log(headers["X-Total-Count"]); //PRINT: undefined
      console.log(headers) //PRINT: {Content-Type:application/json;charset=utf-8}
      console.log(data); //PRINT: [{name:'mr x', age:'67'}, ....]

    },
    function (error) {
      console.error(error);
    });

Model:

myApp.factory("Persons", function ($resource) {
  return $resource(api_url+"/persons");
});

Response Chrome or Firefox, any client:

Access-Control-Allow-Methods:GET
Access-Control-Allow-Origin:*
Content-Length:1839
Content-Type:application/json; charset=utf-8
Date:Thu, 12 Mar 2015 21:53:54 GMT
X-Total-Count:150
like image 469
Mr SC Avatar asked Mar 17 '23 18:03

Mr SC


1 Answers

You're making a request from a different domain than the one where your API is located, operation which is called Cross-site HTTP requests ( CORS )

In order to use custom headers you need to set another one called Access-Control-Expose-Headers

If you want clients to be able to access other headers, you have to use the Access-Control-Expose-Headers header. The value of this header is a comma-delimited list of response headers you want to expose to the client.

This header lets a server whitelist headers that browsers are allowed to access. For example:

Access-Control-Expose-Headers: X-My-Custom-Header,X-Another-Custom-Header 

This allows the X-My-Custom-Header and X-Another-Custom-Header headers to be exposed to the browser.


The way I do it in .NET ( I suppose it's kinda similar in Go):

HttpContext.Current.Response.AppendHeader("Access-Control-Expose-Headers", "X-Total-Pages, X-Records");
HttpContext.Current.Response.AppendHeader("X-Total-Pages", pages.ToString());
HttpContext.Current.Response.AppendHeader("X-Records", records.ToString());

And in AngularJS I'm getting headers like this :

var headers = headers();
headers['x-total-pages']
like image 103
Cosmin Avatar answered Mar 30 '23 17:03

Cosmin