0

I have created a working React Web-app that takes inputs from user. I am trying to add a functionality that, upon clicking a submit button, allows the entire input to be passed to a Flask back-end which processes it further and displays the results back on the screen. How should I proceed to build a simple Flask back-end? How should I formulate my POST request? I am trying to play with the code but getting errors.

My App.js code is given below. I am having trouble in the POST request inside the handleFinalSubmit function.

import React, {Component} from 'react';
import {Footer} from "./Footer";
import {Nav} from "./Nav";
import {Jumbtron} from "./Jumbtron";
import {AddItem} from "./AddItem";
import {DropdownComponent} from "./Component.js";
import {DropdownTLMInstance} from "./TLMInstance.js";
import {DropdownMaskType} from "./MaskType.js";
import Form from "./Form.js";
import Table from "./Table.js";
import axios from 'axios';

class App extends Component {
  constructor(props){
    super(props)
    this.state=this.getInitialState();
  }

  getInitialState =() => ({
    MaskList: [],
  })

  resetState=()=> {
    this.setState(this.getInitialState)
  }


removeMask  = index => {
  const { MaskList } = this.state

  this.setState({
    MaskList: MaskList.filter(( Mask, i) =>{
      return i!==index
    }),
  });
}

  handleSubmit = Mask => {
        this.setState({MaskList: [...this.state.MaskList, Mask]});
    }

// This below is the part where I'am stuck
  handleFinalSubmit = event => {
    event.preventDefault();

    const user = {
      MaskList: this.state.MaskList,
    };

    const requestOptions = {
      method : 'POST',
      cache: 'no-cache',
      headers : { 'Content-Type' : 'application/json' },
      body : JSON.stringify({
        "title" : "React App",
        "body" : user,
        "userId" : "1",
      })
    };

    fetch('http://localhost:5000/result', requestOptions)
      .then(response => response.json()
      )
      .then(json => {
        console.log(json)
      })

      this.resetState();
  }

  render() {
    const {MaskList} = this.state;

    return (
      <div style={{ overflowX: 'hidden' }}>
        <Nav/>
        <Jumbtron/>
        <div className="container">
          <div className="row">
            <div className="col-sm">
              <DropdownComponent/>
            </div>
            <div className="col-sm">
              <DropdownTLMInstance/>
            </div>
            <div className="col-sm">
              <DropdownMaskType/>
            </div>
          </div>
        <AddItem/>
      </div>
        <div className="container">
          <Form handleSubmit={this.handleSubmit}  />
            <hr/>
        </div>
        <Table MaskData={ MaskList } removeMask={ this.removeMask }/>

        <form onSubmit={this.handleFinalSubmit} action="http://localhost:5000/result" method="get">
          <div className="text-center m-4">
            <button type="submit" className="btn btn-success">Submit Request</button>
          </div>
        </form>

        <hr/>
        <Footer/>
      </div>
    )
  }
}

export default App;

The Flask python file that I am trying to create is given below. The current functionality is to simply pass the information stored in React state to Flask and give it back to the web-app.

from flask import Flask, request, jsonify, send_from_directory
from flask_cors import CORS
app = Flask(__name__)
CORS(app)

@app.route('/result', methods = ['GET','POST'])

def result():
    MaskList = request.json
    if MaskList:
        return jsonify(MaskList)
    return "No Information is given"

if __name__ == '__main__':
    app.run(debug=True)

I am confused about the localhost ports where both React and Flask work and the exact structure of my POST request. My package.json file is given below :

{
  "name": "my-project",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "axios": "^0.19.2",
    "prop-types": "^15.6.0",
    "react": "^16.2.0",
    "react-dom": "^16.2.0",
    "react-scripts": "1.0.17"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test --env=jsdom",
    "eject": "react-scripts eject"
  }
}

I want a simple POST request to post React data to Flask back-end and give it back to the front-end.

VITTHAL BHANDARI
  • 139
  • 2
  • 5
  • 15
  • Does this answer your question? [react frontend connecting to flask backend Howto](https://stackoverflow.com/questions/48777708/react-frontend-connecting-to-flask-backend-howto) – metatoaster Jun 15 '20 at 11:02
  • Not exactly. That example is very simple and doesn't serve my purpose. – VITTHAL BHANDARI Jun 15 '20 at 15:54

0 Answers0