【问题标题】:React submit to Flask POST method not writing to database (using Axios)React 提交到 Flask POST 方法不写入数据库(使用 Axios)
【发布时间】:2019-02-19 05:37:40
【问题描述】:

我正在运行一个非常简单的 React 应用程序与 Flask 应用程序通信,读取和写入 MySQL 数据库。我试图从一个简单的网页开始,您在文本框中键入文本,单击按钮,然后在数据库中写入一个新条目。

问题是,我无法将文本从 React 应用程序传递到数据库中。

这是我的 Flask 应用程序:

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

到目前为止,这是我的 signup.jsx 文件:

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;

我已经运行了它,它可以工作:

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

这不是读/写问题,也不是连接问题;这似乎是一个编码错误。

当我单击提交时收到此消息:

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

但是,当我在 MySQL Workbench 中查询表时,没有新数据。

React 应用在 localhost:3000 上运行,Flask 应用在 http://127.0.0.1:5000/ 上运行

我哪里出错了?

编辑 我编辑了我的代码并添加了一些警报和打印。当我从 signup() 方法打印时,什么都没有打印。 在 handleSubmit 函数中,我总是收到一个错误警报,说存在“错误:网络错误”

编辑 我将 CORS 添加到 Flask 应用程序中。数据被写入了,但是Axios在Flask中给出了500的代码:

127.0.0.1 - - [19/Feb/2019 20:59:31] "POST /signup HTTP/1.1" 500 -

【问题讨论】:

  • 嗨,你可以试试这个req_name = request.form['name'] 然后再做addData = Person(name=req_name) 吗?我从这里引用:tutorialspoint.com/flask/flask_http_methods.htm
  • 那行不通
  • 我收到一条错误警报,提示存在“错误:网络错误”,并且 axios.post 似乎根本没有发生。
  • 在您的帖子中,我可以看到这一行 127.0.0.1 - - [19/Feb/2019 00:22:26] "OPTIONS /signup HTTP/1.1" 200 -,我假设它来自后端服务器日志,所以我猜 axios 调用更早工作。那正确吗?另外,不知道这是否是问题(很可能不是),您能否在axios.post 中使用正确的单引号而不是您使用的重音字符。
  • @ArpitAgrawal 我尝试了双引号,但仍然出现同样的问题。来自后端服务器的 200 代码仍然发生,但没有数据写入数据库,并且我在 Axios 上收到网络错误。

标签: mysql reactjs flask axios flask-sqlalchemy


【解决方案1】:

Axios 默认以json 发送数据。因此,您需要从请求正文中以JSON object 的形式获取 Flask 中的数据。

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

【讨论】:

    【解决方案2】:

    问题是我收到了网络错误。我必须启用 CORS 才能让我的交易正常工作。

    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)
    

    【讨论】:

      猜你喜欢
      • 2019-02-11
      • 2020-12-31
      • 1970-01-01
      • 2017-09-17
      • 1970-01-01
      • 1970-01-01
      • 2018-10-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多