我尝试使用AngularJS调用本地运行的REST API。这是AngularJS代码:
$http.defaults.headers.common = {"Access-Control-Request-Headers": "accept, origin, authorization"};
$http.defaults.headers.common['Authorization'] = 'Basic amF5M2RlYzpqYXk=';
$http({method: 'GET', url: 'http://127.0.0.1:5000/user/jay3dec'}).
success(function(data, status, headers, config) {
}).
error(function(data, status, headers, config) {
alert(data);
});
但我在浏览器控制台中收到错误:
Refused to set unsafe header "Access-Control-Request-Headers"
我尝试使用CURL查询调用http://127.0.0.1:5000/user/jay3dec上运行的REST API。
curl -H "Origin: http://127.0.0.1:8000" -H "Authorization: Basic amF5M2RlYzpqYXk=" http://127.0.0.1:5000/user/jay3dec --verbose
它提供了以下输出:
> GET /user/jay3dec HTTP/1.1
> User-Agent: curl/7.35.0
> Host: 127.0.0.1:5000
> Accept: */*
> Origin: http://127.0.0.1:8000
> Authorization: Basic amF5M2RlYzpqYXk=
>
* HTTP 1.0, assume close after body
< HTTP/1.0 200 OK
< Content-Type: application/json
< Content-Length: 454
< ETag: bff7b7db33baedb612276861e84faa8f7988efb1
< Last-Modified: Tue, 30 Dec 2014 14:32:31 GMT
< Access-Control-Allow-Origin: *
< Access-Control-Allow-Headers: Authorization
< Access-Control-Allow-Methods: HEAD, OPTIONS, GET
< Access-Control-Allow-Max-Age: 21600
< Server: Eve/0.4 Werkzeug/0.9.6 Python/2.7.6
< Date: Sun, 25 Jan 2015 20:00:29 GMT
<
* Closing connection 0
{"username": "jay3dec", "_updated": "Tue, 30 Dec 2014 14:32:31 GMT", "password": "jay", "firstname": "jay", "lastname": "raj", "phone": "9895590754", "_links": {"self": {"href": "/user/54a2b77f691d721ee170579d", "title": "User"}, "parent": {"href": "", "title": "home"}, "collection": {"href": "/user", "title": "user"}}, "_created": "Tue, 30 Dec 2014 14:32:31 GMT", "_id": "54a2b77f691d721ee170579d", "_etag": "bff7b7db33baedb612276861e84faa8f7988efb1"}
任何人都可以发现可能存在的问题吗?
答案 0 :(得分:9)
$http.defaults.headers.common
背后的代码是
var xhr = createXhr();
xhr.open(method, url, true);
forEach(headers, function(value, key) {
if (isDefined(value)) {
xhr.setRequestHeader(key, value);
}
});
...
function createXhr() {
return new window.XMLHttpRequest();
}
参考XMLHttpRequest specification,如果标头与以下标头之一不区分大小写,则浏览器将终止
Accept-Charset
Accept-Encoding
Access-Control-Request-Headers
Access-Control-Request-Method
Connection
Content-Length
...
这就是为什么您无法使用$http.defaults.headers.common
设置Access-Control-Request-Headers
标头的原因。浏览器会为您处理请求标头。
答案 1 :(得分:3)
问题出在CORS
您应该配置服务器端以允许在标头中进行授权。我不知道你用于服务器,但我的asp.net web api 2服务器看起来像:
的Web.config
<system.webServer>
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*" />
<add name="Access-Control-Allow-Headers" value="Content-Type,Authorization" />
<add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE, OPTIONS" />
</customHeaders>
</httpProtocol>
......
答案 2 :(得分:0)
出于安全原因,浏览器不允许head设置一些安全风险,例如 cookie ,主机, referer < / strong>等等,所以,不要使用浏览器来解析行头。它可以在服务器端设置的代理服务器上使用。 参考:Cross origin resource sharing