0

Problem: I am trying to send data from React frontend to the backend server which is running flask. I am attempting to send data in which a user enters in information within a form, which is in react frontend.

My Attempt: I know the backend and frontend are able to communicate because I have tested with a GET function as such:

@app.route('/get',methods=['GET'])
def testGet():
        return {
            'name': 'Hello World'
        }

I tested this by using a hook within App.js, this is the following code:

useEffect(() => {
    fetch('http://localhost:5000/get').then(response => {
      if(response.ok){
        return response.json()
      }
    }).then(data => console.log(data))
  },[])

This useEffect correctly displays the message from the backend to the console. I am having a real hard time getting a POST to work. I get the following errors when attempting to POST. This error is on the backend:

The method is not allowed for the requested URL.

This is the error on the frontend:

Cannot POST /

The following code is what I am using to get input from the user to POST to the backend:

<form method="post">
       
          <label>Input</label>
          <input type="variable" name="variable" />
          <input type="submit" value="Submit" />
    </form>

This is the python backend function for the post:

@app.route('/post',methods=['POST'])
def testPost():
        variable = request.form.get("variable","")
        return jsonify(variable=variable)

I have researched a little and am following this post, but nothing seems to work.

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

Am I missing something really simple here?

Zoe
  • 27,060
  • 21
  • 118
  • 148

1 Answers1

1

The Form does the POST request on the root path '/', not on '/post'. You have to specify the path to the form by setting the action attribute for example:

<form method="post" action='/post'>
   
      <label>Input</label>
      <input type="variable" name="variable" />
      <input type="submit" value="Submit" />
</form>

Here is a post example react component:

import { useState } from "react"

function POST(path, data) {
  return fetch(`http://localhost:5000${path}`,
  {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify(data)
    }
  )
}

function MyForm(props) {
  const [text, setText] = useState('Input your name here');
  const [name, setName] = useState('');

  const onChange = e => {
    setText(e.target.value)
  }

  const onClick = e => {
    e.preventDefault();
    POST('/post', {name: text}).then(
      async (resp) => {
        const json= await resp.json()
        console.log(json.name)
        setName(json.name)
      }
    )
  }

  return (
    <div>
    <form>
       
    <label>Input</label>
    <input value={text} onChange={onChange} />
    <input type="submit" value="Submit" onClick={onClick} />
    </form>
    <p>Your name is: <b>{name}</b></p>
    </div>
  )

}

export default MyForm;

And here its corresponding backend with Flask 2.0:

from flask import Flask, request, jsonify, current_app
from flask_cors import CORS

app = Flask(__name__)

@app.post('/post')
def testPost():
    name = request.json.get('name')
    current_app.logger.debug(name)
    return jsonify(name=name)


# because backend and frontend use different ports, we have to enable cross-origin requests
cors = CORS(app, resources={'/*':{'origins': 'http://localhost:3000'}}) 

if __name__ == "__main__":
    app.run()
Adrian Mole
  • 49,934
  • 160
  • 51
  • 83
jvllmr
  • 350
  • 2
  • 11
  • Thank you, it works perfect. The project still works though I am getting an error: Instance of 'Flask' has no 'post' member. Should I be worried about this? – Justin Philip Fulkerson Sep 05 '21 at 14:11
  • No, you shouldn't be worried about it. This is because I was using Flask 2.0 in my example. In Flask 2.0 you can use '@app.post' instead of '@app.route("/", methods=["POST"])'. If you want to use a version below 2.0 you can just keep using app.route, it doesn't even matter on Flask 2.0 which method you use. – jvllmr Sep 05 '21 at 14:18