Home > Net >  Cant send data to flask from react
Cant send data to flask from react

Time:09-02

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

        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>
    )
  }
}

CodePudding user response:

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.

  • Related