Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Cant send data to flask from react

I am trying to post data to flask server from react client. I am not getting the form data in flask.

Flask code for server

@app.route("/imgtest", methods=["POST", "GET"])
def img_test():
    if request.method == 'POST':
        print("From inside post")
        print(list(request.form))
    return jsonify({"Hello": "World"})

react code for client

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

        fetch('/imgtest', {
          method: 'POST',
          headers: {'Content-Type': 'application/json'},
          body: JSON.stringify('message'),
        })

On the server side, I am getting I am getting the the following output.

127.0.0.1 - - [02/Sep/2022 20:16:25] "POST /imgtest HTTP/1.1" 200 -
From inside post
[]

Any ideas would be very helpful. Thanks.

class PasteImage extends React.Component{
  render(){
    return (
      <div className="jumbotron" style={{background : "gray"}} 
        onClick={(e)=> 
          {    
            const formData = new FormData();
            formData.append("name", "My Name")
            
            fetch('/imgtest', {
              method: 'POST',
              headers: {'Content-Type': 'application/json'},
              body: JSON.stringify('message'),
            })
          }
        }>
        <p>
          Hello World! 
        </p>
      </div>
    )
  }
}

>Solution :

You’re sending a JSON body, not a form.

Use request.get_json() to read it, not request.form.

@app.route("/imgtest", methods=["POST", "GET"])
def img_test():
    if request.method == 'POST':
        print(request.get_json())
    return jsonify({"Hello": "World"})

If you do want to send that FormData you construct, then do so (and don’t set the content-type header; fetch does that for you):

const formData = new FormData();
formData.append("name", "My Name");
fetch('/imgtest', {
  method: 'POST',
  body: formData,
});

With this, you’d use request.form in the backend.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading