【问题标题】:Cross domain Angular JSONP request to Python Bottle对 Python Bottle 的跨域 Angular JSONP 请求
【发布时间】:2017-08-14 20:41:37
【问题描述】:

我正在尝试使用 AngularJS 向 Bottle 发出跨域 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"})

错误:

【问题讨论】:

    标签: python angularjs ajax jsonp bottle


    【解决方案1】:

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

    【讨论】:

    • 完美!谢谢!
    • 会的!出于某种原因,我以前从未真正想过这样做..
    • 在我看来,request.query.callback 不是(等效于)True,即使我使用 jQuery AJAX jsonp 调用。知道发生了什么吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-02-24
    • 1970-01-01
    • 2010-11-11
    • 2013-10-29
    • 2012-09-08
    • 2015-01-24
    • 2017-01-11
    相关资源
    最近更新 更多