Bottle + AngularJS - CORS拒绝工作

时间:2014-06-24 19:27:22

标签: javascript python angularjs bottle

Code:

@route('/characteristicsToBestWeb', method='OPTIONS')
def respondToCharToBestQueryWebOptions():
    response.headers['Access-Control-Allow-Origin'] = settings.allowed_web_origin
    response.headers['Access-Control-Allow-Credentials'] = 'true'
    # response.headers['Access-Control-Allow-Origin'] = '*'
    response.headers['Access-Control-Allow-Methods'] = 'POST, OPTIONS'
    response.headers['Access-Control-Allow-Headers'] = 'Origin, Accept,' \
                                                       ' Content-Type,' \
                                                       ' Cache-Control,' \
                                                       ' Pragma,' \
                                                       ' X-Requested-With,' \
                                                       ' X-CSRF-Token'

@route('/characteristicsToBestWeb', method='POST')
def respondToCharToBestWebQuery():
    response.headers['Access-Control-Allow-Origin'] = settings.allowed_web_origin
    response.headers['Access-Control-Allow-Credentials'] = 'true'
    # response.headers['Access-Control-Allow-Origin'] = '*'
    response.headers['Access-Control-Allow-Methods'] = 'POST, OPTIONS'
    response.headers['Access-Control-Allow-Headers'] = 'Origin, Accept,' \
                                                       ' Content-Type,' \
                                                       ' Cache-Control,' \
                                                       ' Pragma,' \
                                                       ' X-Requested-With,' \
                                                       ' X-CSRF-Token'
    render_response()

如您所见,我明确指定了原点,但我在控制台中使用vanilla $http服务和Restangular获得了以下错误。

关于帖子请求:

XMLHttpRequest无法加载http://vitamiter.com/characteristicsToBestWeb。 No' Access-Control-Allow-Origin'标头出现在请求的资源上。起源' http://dev.vitapersonal.com:9000'因此不允许访问。

虽然OPTIONS请求返回正常。

非常感谢任何帮助。

编辑: 使用XMLHttpRequest工作得很好:

    var req = new XMLHttpRequest();
    req.open("POST", API_ROOT + 'characteristicsToBest?cacheBuster=' + Math.random().toFixed(5) , true);
    req.setRequestHeader("Content-Type", "application/json");
    req.setRequestHeader("Cache-Control", "no-cache, must-revalidate");
    req.setRequestHeader("Pragma", "no-cache");
    req.onload = function(){
        var response = this.response;
        $scope.$apply(function(){
            console.log(response)
        })
    }
    req.send(JSON.stringify(reqData));

WT * -angular?

1 个答案:

答案 0 :(得分:0)

试试这个:

@hook('after_request')
def enable_cors():
    response.headers['Access-Control-Allow-Origin'] = '*'
    response.headers['Access-Control-Allow-Methods'] = 'PUT, GET, POST, DELETE'
    response.headers['Access-Control-Allow-Headers'] = 'Origin, Accept, Content-Type, X-Requested-With, X-CSRF-Token'