加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

获取自己的头文件$Resource AngularJs

发布时间:2020-12-17 17:20:50 所属栏目:安全 来源:网络整理
导读:我有GO语言的REST API和 Angularjs中的前端,但是当我在angular中获取我的资源时,我的自定义头文件不存在. 控制器: Persons.query( function (data,headerGetter,status) { var headers = headerGetter(); console.log(headers["X-Total-Count"]); //PRINT:
我有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']

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读