Python Flask从AngularJS AJAX中检索POST数据

时间:2017-02-28 06:55:26

标签: python angularjs json ajax flask

我正在使用Angular AJAX调用将数据发送到我的Flask后端以进行自然语言处理。

AJAX代码:

$scope.processText = function(){

    $http({
        method: "POST",
        url: "http://127.0.0.1:5000/processText",
        headers: {
            'Access-Control-Allow-Origin': '*',
            'Content-Type': 'application/json',
        },
        data: {
            'message': "this is my message",
        }
    }).then(function successCallback(response){
        console.log(response.data)
        $scope.message = "";
    });
}

我能够检索一个对象{消息:&#34;这是我的消息&#34;}但遗憾的是我无法通过输入request.data.message来访问该密钥。< / p>

烧瓶路线

@app.route('/processText', methods=['POST'])

def analyzeText():
    if request.method == "POST":

        data = json.loads(request.data)
        return data         #error : "dict is not callable"
        return data.message #error : "'bytes' object has no attribute 'message'"

2 个答案:

答案 0 :(得分:1)

您需要使用jsonify返回对象,因为jsonify会创建一个自动具有Content-Type标头的flask.Response()对象。

尝试使用此:return jsonify(data)

或者,如果您想要返回字符串(消息的值),您可以继续返回值,就像任何字典值一样,即return data['message']

答案 1 :(得分:1)

这应该适合你。

from flask import jsonify, request
...
message = request.json['message']
return jsonify({'some_message':message})

如果您感到困惑,则无法在Python中交换request.json.messagerequest.json['message']。后者是唯一的选择。它将在Django模板中工作,但这是另一个故事。

https://www.tutorialspoint.com/python/python_dictionary.htm