问题描述
我已经写了使用Python EVE框架的API。虽然试图从AngularJS应用程序访问API它显示了一个错误,如下所示:
I have written an API using Python EVE framework. While trying to access the API from an AngularJS app it shows an error as shown below :
XMLHttpRequest cannot load http://127.0.0.1:5000/user/jay3dec. Request header field Authorization is not allowed by Access-Control-Allow-Headers.
为了纠正上述错误添加以下到settings.py
In order to correct the above error I added the following to the settings.py
X_DOMAINS = '*'
X_HEADERS = 'Authorization'
现在上面的错误消失,在控制台中新的错误表明:
Now the above error disappears and a new error shows in the console :
XMLHttpRequest cannot load http://127.0.0.1:5000/user/jay3dec. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8000' is therefore not allowed access.
不过,我已经添加了 X_DOMAINS ='*'
在我的settings.py。
But I have already added the X_DOMAINS = '*'
in my settings.py .
下面是angularjs code:
Here is the angularjs code:
$scope.validate = function() {
var encodedUserNameAndPassword = Base64.encode($scope.username + ':' + $scope.password);
$http.defaults.headers.put = {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'GET, POST, PUT, DELETE, OPTIONS',
'Access-Control-Allow-Headers': '*'
};
$http.defaults.headers.common['Authorization'] = 'Basic ' + encodedUserNameAndPassword;
$http({
method: 'GET',
url: 'http://127.0.0.1:5000/user/jay3dec'
}).
success(function(data, status, headers, config) {
console.log(data);
}).
error(function(data, status, headers, config) {
alert(data);
});
}
可以在任何点可能是什么问题。
Can any spot what may be the issue
推荐答案
FWIW,我有类似的问题。
FWIW, I had similar problem.
后来我才了解到,只有模式定义的API将得到X_DOMAINS头的效果。该API如果有的话,你在你自己定义使用像应用程序=夏娃(设置=等等)
和 @ app.route()
不会被X_DOMAINS头的影响。所以,在这种情况下,你需要编写自己的装饰。
Then I learned that only schema defined APIs will get the effect of X_DOMAINS header. The api if any you define on your own using something like app = Eve(settings=blah)
and the @app.route()
will not be affected by the X_DOMAINS header. So, in that case, you need to write your own decorator.
这篇关于Python的前夜:无“访问控制允许来源”标头的请求的资源present的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!