Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cross domain Angular JSONP request to Python Bottle

I'm trying to do a cross-domain JSONP request with AngularJS to Bottle, but I'm getting an error.

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

Bottle:

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

Error:

like image 814
Marcus Holm Avatar asked Dec 30 '25 13:12

Marcus Holm


1 Answers

You need to return an JavaScript application (wrapper function in this case) not an json object. This site explains you the basics of 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"))
like image 139
lin Avatar answered Jan 01 '26 04:01

lin