0
votes

I am running a very simple React app communicating to a Flask app, reading and writing to a MySQL database. I am trying to start with a simple web page where you type text into a textbox, click the button, and this writes in the database with a new entry.

Problem is, I cannot get the text to pass from the React app into the database.

Here is my Flask app:

from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask import request
from flask_cors import CORS


app = Flask(__name__)
CORS(app)
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql://root:password@localhost/testdb'

db = SQLAlchemy(app)

class Person(db.Model):
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    name = db.Column(db.String(80), unique=False, nullable=False)

@app.route('/signup', methods = ['GET', 'POST'])
def signup():
    if request.method == 'POST':
        json_data = request.get_json()
        addData = Person(name=json_data.get('name'))
        db.session.add(addData)
        db.session.commit()

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

Here is my signup.jsx file so far:

import React, { Component } from 'react';
import './signup.css';
import axios from 'axios';

class Signup extends Component {
    constructor(props){
        super(props);
        this.state = {
            name: ''
        }
        this.handleChange = this.handleChange.bind(this);
        this.handleSubmit = this.handleSubmit.bind(this);
    }

    handleChange(event){
        this.setState({ name: event.target.value });
    }

    handleSubmit(event){
        alert('test');
        event.preventDefault(); //What is this?
        const name = {
            name: this.state.name
        };
        alert(JSON.stringify(name));
        axios.post(`http://127.0.0.1:5000/signup`, {name})
        .then(res => {
            console.log(res);
            console.log(res.data);
            alert(this.state.name);
        })
        .catch(err => {
            console.log(err);
            alert(err);
        });
    }

    render(){
        return (
            <div className='signup'>
                <form onSubmit={this.handleSubmit}>
                    <input type='text' name='name' onChange={this.handleChange}/><br/>
                    <input type='submit' value='Submit'/>
                </form>
            </div>
        );
    }
}

export default Signup;

I have run this, and it work:

eg = Person(name='what')
db.session.add(eg)
db.session.commit()

It's not a read/write nor a connection problem; it seems to be a coding error.

I get this message when I click the Submit:

127.0.0.1 - - [19/Feb/2019 00:22:26] "OPTIONS /signup HTTP/1.1" 200 -

However, when I query the table in MySQL Workbench, there is no new data.

The React app runs on localhost:3000 and the Flask app runs on http://127.0.0.1:5000/

Where a I going wrong?

EDIT I edited my code and added some alerts and prints. When I print from the signup() method, nothing ever prints. In the handleSubmit function, I always get an error alerting saying that there is a 'Error: Network Error'

EDIT I added CORS to the Flask application. The data gets written, but Axios gives a 500 code in Flask:

127.0.0.1 - - [19/Feb/2019 20:59:31] "POST /signup HTTP/1.1" 500 -
2
Hi, can you try this req_name = request.form['name'] and then do addData = Person(name=req_name) ? I am referencing from here : tutorialspoint.com/flask/flask_http_methods.htm - Arpit Agrawal
That didn't work - God Complex
I get an error alerting saying that there is a 'Error: Network Error', and axios.post doesn't seem to happen at all. - God Complex
in your post i can see this line 127.0.0.1 - - [19/Feb/2019 00:22:26] "OPTIONS /signup HTTP/1.1" 200 - which i am assuming is from backend server log, so i guess axios call was working earlier. Is that right? Also, dont know if this is the issue or not(most likely not), can you use proper single quotes in axios.post instead of accent character you have used. - Arpit Agrawal
@ArpitAgrawal I tried double quotes and it still gives the same problem. The 200 code from the backend server still happens, but no data gets written to the database, and I get the Network Error on Axios. - God Complex

2 Answers

0
votes

Axios sends by default data as json. So you need to get the data in Flask from the request body as a JSON object.

from flask import request

@app.route('/signup', methods = ['GET', 'POST'])
def signup():
    if request.method == 'POST':
        json_data = request.get_json()
        addData = Person(name=json_data.get('name'))
        db.session.add(addData)
        db.session.commit()
0
votes

The issue was that I was receiving a network error. I had to enable CORS in order to get my transactions to work.

handleSubmit(event){
    event.preventDefault();
    const name = {
        name: this.state.name
    };
    axios.post(`http://127.0.0.1:5000/signup`, {name})
    .then(res => {
        console.log(res);
        console.log(res.data);
    })
    .catch(err => {
        console.log(err);
        alert(err); //See this error
    });
}

from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask import request
from flask_cors import CORS


app = Flask(__name__)
CORS(app)