Python Eve:请求的资源上没有“Access-Control-Allow-Origin”标头

我使用
Python EVE框架编写了一个API.尝试从AngularJS应用程序访问API时,它会显示错误,如下所示:

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中

X_DOMAINS = '*'
X_HEADERS = 'Authorization'

现在,上述错误消失,控制台中显示一个新错误:

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. 

但是我已经在settings.py中添加了X_DOMAINS =’*’.

这是angularjs代码:

    $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);

    });
}

可以发现任何问题

最佳答案 FWIW,我有类似的问题.

然后我了解到只有模式定义的API才能获得X_DOMAINS标头的效果.如果您使用app = Eve(settings = blah)和@ app.route()等自己定义的api将不受X_DOMAINS标头的影响.所以,在这种情况下,你需要编写自己的装饰器.

点赞