Flask与axios 前后端交互
axios 是一个更好的替代ajax向后端发送数据或请求数据的前端组件库,运用axios向后端提交JSON字符串,后端通过Flask相应请求并处理的一个案例。
前端发送数据的第一种方式。
前端发送数据的第二种方式。
Python后端使用Flask接收并处理前端发送过来的JSON字符串。
from flask import Flask
from flask import render_template,request
import json
app = Flask(__name__)
@app.route('/',methods=['GET','POST'])
def hello_world():
if request.method == "GET":
return render_template("index.html")
elif request.method == "POST":
val = request.get_json()
print("收到用户: {} ---> 年龄: {}".format(val["name"],val["age"]))
# 返回JSON类型
return json.dumps({"username": "lyshark","message": "hello lyshark"})
if __name__ == '__main__':
app.run()