2

I am new to React and Flask API system. I created a website that allows a user to search via a search bar. I want to be able to send the query from the React search bar to the Flask API via a POST request. However I get either an empty string or ImmutableDict

React code

function handlePostQuery(query){

    if (query != "") {
        axios.post('http://localhost:5000/api/query', query)
            .then(function(response){
                console.log(response);
       //Perform action based on response
        })
        .catch(function(error){
            console.log(error);
       //Perform action based on error
        });
    } else {
        alert("The search query cannot be empty")
    }
}

Flask code

@app.route('/api/query', methods = ['POST'])
def get_query_from_react():
    data = request.form
    print(data)
    return data

Following this answer: Get the data received in a Flask request

I tried all of them, but I always get (in Flask) an empty string unless I use request.form which returns me something like:

ImmutableMultiDict([('what I type in the searchbar', '')])

However in the webconsole I get:

config: {url: "http://localhost:5000/api/query", method: "post", data: "what I type in the search", headers: {…}, transformRequest: Array(1), …}
    data: {what I type in the search: ""}
    headers: {content-length: "38", content-type: "application/json"}
    request: XMLHttpRequest {readyState: 4, timeout: 0, withCredentials: false, upload: XMLHttpRequestUpload, onreadystatechange: ƒ, …}
    status: 200
    statusText: "OK"
    __proto__: Object

I am assuming axios already return a JSON from React. So I do not think that is a problem.

Prova12
  • 643
  • 1
  • 7
  • 25

1 Answers1

5

You can try the following:

React

function handlePostQuery(query){

    var myParams = {
        data: query
    }

    if (query != "") {
        axios.post('http://localhost:5000/api/query', myParams)
            .then(function(response){
                console.log(response);
       //Perform action based on response
        })
        .catch(function(error){
            console.log(error);
       //Perform action based on error
        });
    } else {
        alert("The search query cannot be empty")
    }
}

Flask

@app.route('/api/query', methods = ['POST'])
def get_query_from_react():
    data = request.get_json()
    print(data)
    return data

I think the problem was that Axios was not reading correctly the JSON. That is why I created the myParams dictionary and pass to Axios.

Magofoco
  • 5,098
  • 6
  • 35
  • 77