[英]Add a custom header in http get request angularjs.
这是我的angularjs请求。
var req = {
method: 'GET',
url: 'http://localhost:8080/test',
headers: {
"x-auth-token" : user.token
}
}
$http(req).success(function(){
console.log("yes you have done it");
}).error(function(){
console.log("oopsss");
});
当我调用此请求时,出现了此异常。
XMLHttpRequest无法加载http:// localhost:8080 / test 。 无效的HTTP状态代码403
但是,在谷歌浏览器的邮递员测试中,它运行良好,并按预期返回了响应。 我得到这个。
邮递员测试中的请求标头
GET /appraisal HTTP/1.1
Host: localhost:8080
Connection: keep-alive
Cache-Control: no-cache
x-auth-token: 123456
User-Agent: Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.101 Safari/537.36
Accept: */*
Accept-Encoding: gzip, deflate, sdch
Accept-Language: en-GB,en-US;q=0.8,en;q=0.6
并在响应头中。
Access-Control-Allow-Origin:*
Cache-Control:no-cache, no-store, max-age=0, must-revalidate
Content-Type:application/json;charset=UTF-8
Date:Fri, 27 Mar 2015 16:13:46 GMT
Expires:0
Pragma:no-cache
Server:Apache-Coyote/1.1
Transfer-Encoding:chunked
X-Content-Type-Options:nosniff
X-Frame-Options:DENY
X-XSS-Protection:1; mode=block
但是,当我调用我的get请求时,浏览器会显示这样的http请求标头。
Accept:*/*
Accept-Encoding:gzip, deflate, sdch
Accept-Language:en-GB,en-US;q=0.8,en;q=0.6
Access-Control-Request-Headers:accept, x-auth-token
Access-Control-Request-Method:GET
Connection:keep-alive
Host:52.11.111.128:8080
Origin:http://localhost:8080
Referer:http://localhost:8080/james/index.html
User-Agent:Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.101 Safari/537.36
和http响应头是
Access-Control-Allow-Headers:x-auth-token
Access-Control-Allow-Headers:Content-Type
Access-Control-Allow-Methods:GET, POST, PUT, DELETE
Access-Control-Allow-Origin:*
Access-Control-Max-Age:1
Allow:GET, HEAD, POST, PUT, DELETE, TRACE, OPTIONS, PATCH
Cache-Control:no-cache, no-store, max-age=0, must-revalidate
Content-Length:0
Date:Fri, 27 Mar 2015 17:03:16 GMT
Expires:0
Pragma:no-cache
Server:Apache-Coyote/1.1
X-Content-Type-Options:nosniff
X-Frame-Options:DENY
X-XSS-Protection:1; mode=block
我的服务器中启用了跨请求起源策略。
如何正确请求标头?
如何在控制器中解决此问题。
请指导我。
提前致谢。
我们使用一种服务,该服务针对REST-API设置所有请求的标头。 该服务设置了授权标头,如下所示:
app.factory('api', function($http) {
function init(token) {
$http.defaults.headers.common.Authorization = token || 'Basic xyztoken==';
}
return {
init : init
};
});
在我们的app.run上,我们初始化标题:
app.run(function(api, …) {
…
api.init();
…
});
在AuthService上,我们使用新令牌设置授权标头:
app.factory('AuthService', function(api, …) {
…
// some login action with a response from the REST-API and
// set the new authorization header
api.init('Bearer ' + response.data.accessToken);
// some more stuff
…
});
在我们的控制器中,您无需再使用自定义标头。
仅当您使用凭据时才有效。 因此,您必须在应用程序的配置阶段设置withCredential标志:
app.config(function($httpProvider, …) {
…
$httpProvider.defaults.withCredentials = true;
…
});
乔·拉尔夫
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.