【问题标题】:Pulling data from React Form into Json with Flask使用 Flask 将数据从 React Form 拉入 Json
【发布时间】:2021-02-22 02:19:09
【问题描述】:

我想从 React 表单中获取输入并将 JSON 格式的输出提供给烧瓶 API。我有想要传递的动态数据。但是我不知道该怎么做。

反应形式

function App (){
  
  
  const [initialData, setInitialData] = useState([{}]);
  useEffect(() => {
    fetch('/result').then(
      response => response.json()
    ).then(data => setInitialData(data))
  }, []);
  
    return (
      <div className="App">
          <h1 className="header">Twitter Sentiment Analysis</h1>
            <form action="http://localhost:3000/result" method = "POST">
              <div className="forms">
              <label>
                Enter Twitter Handle:
              <input type="text" name="handle" />
              </label>
              <label>
                Enter Number of Tweets (200 Limit):
              <input type="text" name="tCount"/>
              </label>
              </div>
              <div className = "button">
              <input type="submit" method="POST"/>
              </div>
            </form>
  
      </div>
    );
  
}
export default App;

这是我正在使用的 Flask 函数

app = Flask(__name__)
CORS(app)

handle = ''
tCount = 0

@app.route('/result', methods = ['POST'])
def result():
    h = request.json[0]
    c = request.json[1]

    data = {'handle': h, 'tCount': c}

    return jsonify(data)

如何将 React Form 中的变量整齐地转换为 JSON 格式到 Flask 中?

【问题讨论】:

    标签: python reactjs flask frontend backend


    【解决方案1】:

    我认为您可以使用request.form.get(key)request.form[key],而不是使用request.json。所以,我可以改变这段代码

    @app.route('/result', methods = ['POST'])
    def result():
        h = request.json[0]
        c = request.json[1]
    
        data = {'handle': h, 'tCount': c}
    
        return jsonify(data)
    

    @app.route('/result', methods = ['POST'])
    def result():
        # If you have any other keys but don't want to include
        data = {'handle': request.form['handle'], 'tCount': request.form['tCount']}
    
        # If you only have two keys (handle and tCount)
        data = request.form
    
        return jsonify(data)
    

    如需更多方便的信息,您可以在 (https://www.digitalocean.com/community/tutorials/processing-incoming-request-data-in-flask) 阅读更多信息

    【讨论】:

      猜你喜欢
      • 2012-04-28
      • 1970-01-01
      • 1970-01-01
      • 2017-08-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-02-18
      • 1970-01-01
      相关资源
      最近更新 更多