反应前端连接到烧瓶后端Howto [英] react frontend connecting to flask backend Howto

查看:103
本文介绍了反应前端连接到烧瓶后端Howto的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个ReactJS前端和一个烧瓶后端,我很难同时互相交谈,特别是从前端向Flask发送表格变量。

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.

以下是我的前端代码,运行在127.0.0.1:3000

Given below is my front end code which runs on 127.0.0.1:3000

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

我的后端烧瓶代码如下所示,运行于127.0.0.1:5000

My backend flask code is as given below and runs on 127.0.0.1:5000

from flask import Flask, render_template, request
import requests
import json
app = Flask(__name__)
@app.route('/result',methods = ['POST', 'GET'])
def result():
   if request.method == 'GET':
      result = request.form
      print (result['place'])


推荐答案

我已经调整了一点代码。
我所做的更改:

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


  • 添加了后端路径 http:// localhost:5000 / result 在前端作为表单操作路径。

  • 使用 request.args.get 获取提交值的方法。

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

前端在端口3000上运行,后端在端口5000上运行;在 localhost 中。

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

前端代码:

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')
);

后端代码:

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:

参考:

Flask文档:请求对象

这篇关于反应前端连接到烧瓶后端Howto的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆