0

I am using Angular AJAX call to send data to my Flask backend for natural language processing.

AJAX code:

$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 = "";
    });
}

I'm able to retrieve an Object {message: "this is my message"} but unfortunately I'm could not access to the key by typing request.data.message.

Flask route

@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 Answers 2

1

This should work for you.

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

If you are confused, you cannot interchange request.json.message and request.json['message'] in Python. The latter is the only option. It will work in Django templates, but that's another story.

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

Sign up to request clarification or add additional context in comments.

Comments

1

You need to use jsonify to return the object since jsonify creates a flask.Response() object that automatically has the Content-Type header.

Try using this: return jsonify(data)

Alternatively, if you want to return the string (value of message), you can just go ahead and return the value as you would any dict value i.e return data['message']

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.