获取自己的头文件$Resource AngularJs

前端之家收集整理的这篇文章主要介绍了获取自己的头文件$Resource AngularJs前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有GO语言的REST API和 Angularjs中的前端,但是当我在angular中获取我的资源时,我的自定义文件不存在.

控制器:

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

模型:

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

响应Chrome或Firefox,任何客户:

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

解决方法

您从与API所在域不同的域发出请求,该操作称为跨站点HTTP请求(CORS)

要使用自定义标头,您需要设置另一个名为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.

我在.NET中的方式(我想它在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());

在AngularJS中我得到这样的标题

var headers = headers();
headers['x-total-pages']

猜你在找的Angularjs相关文章