How to send data from React to Flask then back to react and show output on DOM

Viewed 4605

Im trying to pass data from React --> Flask --> React and show it in the DOM.

So far I been able to:

  • Send data from React to Flask and display the output on the console. (POST)
  • Send data from flask to React and display it on the DOM (GET)

So now my confusion is how do I put these 2 together. Here is my React code to send my data to Flask Username.js (POST)

##REACT
class Content extends Component {
 login = (e) => {
        e.preventDefault();
        axios
            .post("/username", {
                username: document.getElementById("username").value,
            })
            .then((res) => {
                console.log( res.data);
            });
    };

    

  render() {
    return(

      <div className="p"> <User />

      <form onSubmit={this.login}>
                        <p>
                            <label htmlFor="email">Email</label>
                            <input
                                type="username"
                                className="w3-input w3-border"
                                id="username"
                            />
                        </p>
                        <p>
                            <button type="submit" className="w3-button w3-blue">
                                Login
                            </button>
                        </p>
                    </form>
                   
              </div>      

        
    );
  }
}

And here is how I receive my data on flask

###FLASK
@app.route("/username", methods=['POST'])
def login():
    username = request.json["username"]
    #username = request.args.get('username')
    return {"username": 'This is the backend -- >'+ username }

When adding anything on my input label I can see it on the console. Now what I want is to get the result that I added on the input in the DOM. This can be on another page maybe?

Do I need to create a new route and pass the data from the /username? and then make an API call on my react app to this new route? How can I pass this username output to another route? Is this the right way of doing it?

Please advice thank you

1 Answers

from your front-end code it seems that you are sending a post request of type: application/x-www-form-urlencoded, that it's the default request for html5 form. In your backend logic you're tring to get incoming data as json with the following code request.json["username"]. Instead you should use request.form["username"] or request.form.get("username", "").

Here a little resume:

  • request.args: the key/value pairs in the URL query string

  • request.form: the key/value pairs in the body, from a HTML post form, or JavaScript request that isn't JSON encoded request.files: the files in the body, which Flask keeps separate from form. HTML forms must use enctype=multipart/form-data or files will not be uploaded.

  • request.values: combined args and form, preferring args if keys overlap request.json: parsed JSON data. The request must have the application/json content type, or use request.get_json(force=True) to ignore the content type.

  • request.files: the files in the body, which Flask keeps separate from form. HTML forms must use enctype=multipart/form-data or files will not be uploaded.

  • request.values: combined args and form, preferring args if keys overlap

  • request.json: parsed JSON data. The request must have the application/json content type, or use request.get_json(force=True) to ignore the content type.

Your input field in front-end code should look like this:

<form onSubmit={this.login} method="post">
    <p>
       <label htmlFor="email">Email</label>
       <input type="username" className="w3-input w3-border" id="username" name="username" />
   </p>
   <p>
      <input type="submit" className="w3-button w3-blue" value="Login" />
   </p>
</form>

Changes added :

  • method="post" : default method in html 5 form is GET
  • name="username" : as new attribute for input
  • input type="submit" : instead of button

Your back-end should be like this:

@app.route("/username", methods=['POST'])
def login():
    username = request.form.get("username", "") # or request.form["username"]
    return jsonify(username=username) # from flask import jsonify 

I advice you to use jsonify() to return json data.

Finally in your front-end code if you want to print json response with the collected username should update your code in something like this:

.post("/username", {
      username: document.getElementById("username").value,
})
.then((res) => {
     // JSON response is handled by a json() promises
     return res.json().then( (data) => console.log(data));
});
Related