我的设置标题有问题。我的js脚本
var invocation = new XMLHttpRequest();
var url = 'http://example.com/api/auth';
var handler = [];
if(invocation) {
invocation.open('GET', url, true);
invocation.setRequestHeader('X-PINGOTHER', "DDD");
invocation.setRequestHeader('Access-Control-Allow-Origin', "http://localhost");
invocation.setRequestHeader('Access-Control-Request-Headers', true);
invocation.onreadystatechange = handler;
invocation.send();
}
来自萤火虫的标题:
OPTIONS /api/auth HTTP/1.1
Host: example.com
User-Agent: Mozilla/5.0 (Windows NT 6.2; WOW64; rv:18.0) Gecko/20100101 Firefox/18.0 FirePHP/0.7.4
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Origin: http://localhost
Access-Control-Request-Method: GET
Access-Control-Request-Headers: access-control-allow-origin,x-pingother
x-insight: activate
Connection: keep-alive
如您所见,它始终将Access-Control-Request-Headers作为值添加,并设置OPTIONS no GET。有什么想法吗?
答案 0 :(得分:0)
您应该更好地使用AngularJS附带的$http
:
$http.defaults.useXDomain = true; //enable cors
$http({
method: 'GET',
url: 'http://example.com/api/auth',
headers: {'X-PINGOTHER': 'DDD'}
});
答案 1 :(得分:0)
好吧,它正在发挥作用,但不适用于GET。 它应该如何:
$http({
method: "GET",
url: "http://example.com/api/auth"
}).success(function(data) {
$scope.user = data;
}).error(function(data) {
console.log("error");
});
工作示例:
$http.jsonp('http://example.com/api/auth?&callback=JSON_CALLBACK')
.success(function(data){
console.log(data);
}).error (function(data){
alert("eerrror");
});
仅适用于JSONP。