react frontend connecting to flask backend Howto

后端 未结 1 785
我在风中等你
我在风中等你 2020-12-30 13:20

I have a ReactJS front end and a flask backend and I am having difficulties making both talk to each other, particular sending form variables from the frontend to Flask.

相关标签:
1条回答
  • 2020-12-30 13:49

    I have tweaked your code a little bit. Changes I have made:

    • added the backend path http://localhost:5000/result in frontend as form action path.
    • used request.args.get method to grab the submitted value.

    The frontend is running on port 3000 and the backend is running on port 5000; both in localhost.

    Frontend code:

    import ReactDOM from 'react-dom';
    import React, {Component} from 'react';
    class Form1 extends Component{
        render(){
            return (
                <div class="form">
                    <form action="http://localhost:5000/result" method="get">
                        Place: <input type="text" name="place"/>
                        <input type="submit" value="Submit"/>
                    </form>
                </div>
            );
        }
    }
    ReactDOM.render(
        <Form1/>,
        document.getElementById('root')
    );
    

    Backend Code:

    from flask import Flask, request
    
    app = Flask(__name__)
    
    @app.route('/result', methods = ['GET', 'POST'])
    def result():
        if request.method == 'GET':
            place = request.args.get('place', None)
            if place:
                return place
            return "No place information is given"
    
    if __name__ == '__main__':
        app.run(debug = True)
    

    Here is the screenshot of running program:

    Reference:

    Flask documentation: The request object

    0 讨论(0)
提交回复
热议问题