2

I'm extremely new to React and Python and just trying to do a simple post from a react form to my Python API that will interface with a mongoDB. I have a form in react that invokes a handleSubmit function on submit. I want the handleSubmit function to POST to my Python API running on port 5000. My react app is running on port 8080.

The handleSubmit looks like this:

handleSubmit(event) {
    const axios = require('axios');
    const baseUrl = 'http://localhost:5000'

    axios.post('http://localhost:5000/api/create', JSON.stringify(params))
        .end((error, response) => {
            if (!error && response) {
                console.log('got a valid response from the server')
            } else {
                console.log(`Error fetching data from the server: `, error)
            }
        });

    event.preventDefault();
}

Python endpoint code:

@app.route('/api/create', methods=['POST'])
def create(self):
    if request.method == 'POST':
        print(request.args.get('exp_title'))
        return True
    return False

When I click the button, my python API endpoint isn't reached because react is trying to post to a route on port 8080. What am I missing?

I've tried using a regular ajax call and get the same result. At one point, I did something and got a CORS error in the browser, but I can't remember how I did that.

1 Answer 1

3

To enable cors, you need to install pip install -U flask-cors, here is the website: https://flask-cors.readthedocs.io/en/latest/ or you can define cors in proxy in your reactjs package.json like here: https://facebook.github.io/create-react-app/docs/proxying-api-requests-in-development

Once you install cors in your python app, try this: Python app:

@app.route('/api/', methods=['POST', 'GET'])
def api_post():
    if request.method == 'POST':
        print('post app')
        req = request.json
        print(req)
        return jsonify(name='john')

React app:

function App() {
  const [todos, setTodos] = useState(null);
  const [value, setValue] = useState('');

  function handleSubmit(e) {
    e.preventDefault();
    const data = { name: value };
    console.log('submit');
    console.log(value);
    fetch('http://127.0.0.1:5000/api/', {
      method: 'POST',
      headers: {
        'Content-type': 'application/json',
      },
      body: JSON.stringify(data),
    })
      .then(res => res.json())
      .then(res => console.log(res));
  }

  function handleValue(e) {
    setValue(e.target.value);
  }
  return (
    <section id="app">
      <form action="" onSubmit={handleSubmit}>
        <input type="text" onChange={handleValue} />
        <button> submit </button>
      </form>
    </section>
  );
}
render(<App />, document.querySelector('#root'));
Sign up to request clarification or add additional context in comments.

2 Comments

Your comment gave me a good place to start addressing the problem. I ended up using fetch like in your example and added header values to get pass the CORS issue.
While this is a good example with flask api, i was looking for solution with fast api. I have added CORS settings from here : fastapi.tiangolo.com/tutorial/cors but it still gives me the CORS error.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.