gpt4 book ai didi

angularjs - 获取自己的 header $Resource AngularJs

转载 作者:行者123 更新时间:2023-12-02 23:29:01 24 4
gpt4 key购买 nike

我有一个 GO 语言的 REST API 和 Angularjs 的前端,但是当我以 Angular 形式获取资源时,我的自定义 header 不存在。

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

型号:

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 所在的域不同的域发出请求。位于,名为 Cross-site HTTP requests ( CORS ) 的操作

为了使用自定义 header ,您需要设置另一个名为 Access-Control-Expose-Headers 的 header 。

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 - 获取自己的 header $Resource AngularJs,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29021198/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com