获取自己的标头$ Resource AngularJs [英] Get own headers $Resource AngularJs
问题描述
我有一个使用GO语言的REST API和一个在Angularjs中使用的前端,但是当我用angular获取资源时,我的自定义标头就不存在了.
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.
控制器:
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,任何客户端:
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
推荐答案
您正在从与您的 API
所在的域不同的域发出请求,该操作称为跨站点HTTP请求(CORS)
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 )
要使用自定义标头,您需要设置另一个名为 Access-Control-Expose-Headers
In order to use custom headers you need to set another one called Access-Control-Expose-Headers
如果希望客户端能够访问其他标头,则必须使用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
这允许使用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
中有点类似):
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());
在 AngularJS
中,我得到这样的标题:
And in AngularJS
I'm getting headers like this :
var headers = headers();
headers['x-total-pages']
这篇关于获取自己的标头$ Resource AngularJs的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!