我有一个ReactJS前端和一个烧瓶后端,我很难同时互相交谈,特别是从前端向Flask发送表格变量。
以下是我的前端代码,运行在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
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'])
答案 0 :(得分:7)
我稍微调整了你的代码。 我所做的改变:
http://localhost:5000/result
作为表单操作路径。request.args.get
方法获取提交的值。前端在端口3000上运行,后端在端口5000上运行;都在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)
以下是正在运行的程序的屏幕截图:
<强>参考:强>