[英]react frontend connecting to flask backend Howto
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.我有一个 ReactJS 前端和一个 Flask 后端,我很难让两者相互交谈,特别是从前端向 Flask 发送表单变量。
Given below is my front end code which runs on 127.0.0.1:3000下面给出的是我在 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')
);
My backend flask code is as given below and runs on 127.0.0.1:5000我的后端烧瓶代码如下所示,运行在 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
in frontend as form action path.http://localhost:5000/result
作为表单操作路径。request.args.get
method to grab the submitted value.request.args.get
方法来获取提交的值。 The frontend is running on port 3000 and the backend is running on port 5000;前端运行在3000端口,后端运行在5000端口; both in
localhost
.都在
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:参考:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.