Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
298 views
in Technique[技术] by (71.8m points)

javascript - 如何从React Form-> Flask Backend-> React Component传递数据(它与CORS有关)?(How to pass data from React Form -> Flask Backend -> React Component (does it have something to do with CORS)?)

Hi I am a complete React beginner and have a fairly basic question.

(嗨,我是一个完整的React初学者,并且有一个相当基本的问题。)

I am looking to perform the following steps:

(我希望执行以下步骤:)

(1) Provide user a form to input some text (2) Ingest the input into the Flask backend and return a new value after performing some operations (3) Provide the result from (2) to the user in front end view

((1)向用户提供输入一些文本的表单(2)在执行某些操作后将输入摄取到Flask后端并返回新值(3)在前端视图中将(2)的结果提供给用户)

I'd like this process to be a single page app where the user does not get redirected to another page on step (3).

(我希望此过程是一个单页应用程序,其中用户不会在步骤(3)上重定向到另一页。)

Here is my App.js code:

(这是我的App.js代码:)

import React from 'react';
import './App.css';

class App extends React.Component {

 constructor(props) {
    super(props);
    this.state = {value: '',
                  playerName: ''};

    this.handleChange = this.handleChange.bind(this);
    this.handleSubmit = this.handleSubmit.bind(this);
  }

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

  handleSubmit(event) {
    console.log("making request")
    fetch('/result')
      .then(response => {
        console.log(response)
        return response.json()
      })
      .then(json => {
      console.log=(json)
      this.setState({playerName: json[0]})
      })
  }

  render() {
    return (
      <div>
        <form onSubmit={this.handleSubmit} action="http://localhost:5000/result" method="get">
        <label>
          Player ID:
          <input type="text" name="player_id"/>
          <input type="submit" onChange={this.handleChange} value={this.state.value} />
        </label>
      </form>
        <h1> Player Name: {this.state.playerName} </h1>
      </div>
    );
  }
}


export default App

Here is my main.py code:

(这是我的main.py代码:)

from flask import Flask, request, jsonify, send_from_directory
from sqlalchemy import create_engine
import pandas as pd

app = Flask(__name__, static_folder='../frontend/build')

@app.route('/result', methods = ['GET'])
def result():
    if request.method == 'GET':
        player_id = request.args.get('player_id', None)
        if player_id:
            data = get_player(player_id)
            name = str(data['name'][0])
            return jsonify(name)
        return "No player information is given"


def get_player(player_id):
    engine = create_engine(
        'postgres://fzmokkqt:********************-***-******-@********.com:*****/******')
    sql = """SELECT * from players WHERE id={player_id}"""
    data = pd.read_sql_query(sql.format(player_id=player_id), con=engine)
    return data

@app.route('/', defaults={'path': ''})
@app.route('/<path:path>')
def serve(path):
    if path != "" and os.path.exists("frontend/build/" + path):
        return send_from_directory('../frontend/build', path)
    else:
        return send_from_directory('../frontend/build', 'index.html')

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

When I run this code, I receive the intended result however it is not placed in the HTML as described in the App.js code.

(当我运行此代码时,我收到了预期的结果,但是未按照App.js代码中的说明将其放置在HTML中。)

Instead, the result is rendered into a new page (on localhost:5000 instead of localhhost:3000 which is where the React code is rendered).

(而是将结果呈现到新页面(在localhost:5000上,而不是在本地Hhost:3000上,这是React代码的呈现位置)。)

  ask by Tom Jackson translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
等待大神答复

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...