对 Python Bottle 的跨域 Angular JSONP 请求

Cross domain Angular JSONP request to Python Bottle

我正在尝试使用 AngularJS to Bottle 执行跨域 JSONP 请求,但出现错误。

Angular:

// 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"})

错误:

您需要 return 一个 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"))