A15.从零开始前后端react+flask - 将前后端联系起来
视频链接:https://www.bilibili.com/video/av78415640
前端:react,后端:flask,我们在前面课程中都已经分别单独学习。
那么,怎么把前后端联系起来呢?
这是系列教程,前面基础部分可以查看博客其他内容。
(这节课信息量稍微有点大,建议多看几次)
这里面的坑实在是太多了,我一个一个自己踩过才知道。
添加ApiUtil.js
一些接口,暂时还用不到这么多。
export default class ApiUtil {
static URL_IP = 'http://127.0.0.1:5001';
static URL_ROOT = '/api/v1';
static API_STAFF_UPDATE = ApiUtil.URL_ROOT + '/updateStaff';
static API_STAFF_LIST = ApiUtil.URL_ROOT + '/getStaffList/';
static API_STAFF_DELETE = ApiUtil.URL_ROOT + '/deleteStaff/';
static API_STAFF_SEARCH_3 = ApiUtil.URL_ROOT + '/searchStaff_3'; //只搜索3个属性
static API_CHECK_PASSWORD = ApiUtil.URL_ROOT + '/checkPassword';
static API_ADMIN = ApiUtil.URL_ROOT + '/gotoAdmin'; //进入管理员状态
static API_EXPORT_TO_FILE = ApiUtil.URL_ROOT + '/export_to_file'; //将数据导出到文件
}
添加HttpUtil.js
写get和post方法
export default class HttpUtil{
static get(url){ //我们定义的get函数,只需要指定访问api即可
return new Promise((resolve,reject)=>{
fetch(url)
.then(response=>{
if(response.ok){
return response.json();
}else{
throw new Error(response.status + " : "+response.statusText);
}
})
.then(result=>resolve(result))
.catch(error=>{
reject(error);
})
});
}
static post(url, data){ //而post函数,不仅指定api,还需要从前端传递参数信息过来
return new Promise((resolve,reject)=>{
fetch(url,{
method: 'POST',
headers:{
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify(data)
})
.then(response=>response.json())
.then(result=>resolve(result))
.catch(error=>{
reject(error);
})
})
}
}
GET和POST区别:
https://blog.csdn.net/qq_39539470/article/details/82470360
简单总结:
1,GET请求,请求的数据会附加在URL之后
因此,GET请求的数据会暴露在地址栏中,而POST请求则不会。
2,在使用GET请求时,传输数据会受到URL长度的限制。
3,POST的安全性比GET的高。
修改handleOK函数
handleOK = ()=>{
this.props.form.validateFields((err,values)=>{
if(err){
message.error('表单数据有误,请根据提示填写!')
}else{
// console.log("填写正确!");
HttpUtil.post(ApiUtil.API_STAFF_UPDATE, values)
.then(
re=>{
console.log("返回结果:",re);
message.info(re.message);
}
)
.catch(error=>{
message.error(error.message);
});
this.setState({
visible: false,
});
this.props.onDialogConfirm(values);
}
})
}
在后端的run.py
from flask import Flask, request
import json
app = Flask(__name__, template_folder='../front-end', static_folder='../front-end', static_path='')
@app.route('/hi')
def hi():
return 'hi~'
#api接口前缀
apiPrefix = '/api/v1/'
################## Staff接口 ##################
@app.route(apiPrefix + 'updateStaff', methods=['POST'])
def updateStaff():
data = request.get_data(as_text=True)
re = {
'code': 0,
'data':data,
'message': "这是测试呀"
}
print("后端数据:",data)
return json.dumps(re)
if __name__=="__main__":
app.run(debug=True, port=5001)
其中,对于 app = Flask(...)
app = Flask(__name__, template_folder='../front-end', static_folder='../front-end', static_path='')
自己总结:template_folder 从run.py文件开始定位模板文件(index.html)<找到index.html>。static_folder从run.py开始找资源文件,资源文件在html文件中要用到<给index.html中js提供一个查找位置>。static_url_path=''比较方便
你以为,这样就能成功吗?并没有。
在package.json中加入:
"proxy": "http://127.0.0.1:5001"
如何,刷新一下,结果发现没有变化,简直差点暴捶电脑。因为之前一样的操作是完全可以的。
冷静思考,debug。发现解决办法:
关闭前端服务器,重启!!! npm start
终于成功:
前端结果:
后端结果:

成功,收工,下期见。
注:此套教程有配套视频和代码,详情见
A01.从零开始前后端react+flask - 前面的话+技术介绍:https://blog.csdn.net/GreatXiang888/article/details/103269687
一些有用资料
React学习(五)——向服务器请求数据并显示 https://blog.csdn.net/daxiazouyizou/article/details/79773307
Promise初步详解(resolve,reject,catch) https://blog.csdn.net/weixin_41888813/article/details/82882375
如何理解package.json中的proxy字段?https://segmentfault.com/a/1190000014891894
我们并没有遇到CORS问题,因为在浏览器眼里,我们还是将请求发送到"http://localhost:3000" 中的,它并不知道creat-react-app已经将请求转发到了"http://0.0.0.89:7300" 这个所谓的会触发浏览器CORS安全策略的其他Origin。
antd做form表单的组件共用,利用mapPropsToFields填写默认值 https://www.cnblogs.com/zhuhuoxingguang/p/10938659.html
更多推荐
所有评论(0)