对Python Bottle的跨域Angular JSONP请求

时间:2017-03-22 15:50:27

标签: python angularjs ajax jsonp bottle

我尝试使用AngularJS进行跨域JSONP请求,但我收到错误。

角:

// this angular code is on localhost:8888, so it's cross domain

var URL = "http://localhost:8000/test";
    URL = $sce.trustAsResourceUrl(URL);

$http.jsonp(URL, {jsonpCallbackParam: 'callback'})
.then(function successCallback(response) {
    console.log(response);
}, function errorCallback(error) {
    console.log(error);
});

瓶:

@route('/test')
def test():
    response.headers['Content-Type'] = 'application/json'
    return json.dumps({"random": "JSON"})

错误:

1 个答案:

答案 0 :(得分:2)

您需要返回一个JavaScript应用程序(在本例中为包装函数)而不是json对象。本网站向您解释JSONP handling的基础知识。

def jsonp(request, dictionary):
    if (request.query.callback):
        # wrap the dictionary in the callback parameter
        return "%s(%s)" % (request.query.callback, dictionary)
    return dictionary

@route('/test')
    if (request.query.callback):
        response.content_type = "application/javascript"
    return jsonp(dict(success="It worked"))