这是我的ReactJS代码:
addPerson(firstName, lastName) {
console.log(firstName)
console.log(lastName) // this console logs for example "Peter" and "Becker"
axios.post("http://127.0.0.1:5000/addPerson", {
params: {
firstName, lastName
}
})
.then(res => {
console.log(res.data) //this console logs the return data from python (in this case
//"have a connection"
})
}
这是我的Flask代码:
@app.route("/addPerson", methods=["POST"])
def addPerson():
firstName = request.args.get('firstName', '')
lastName = request.args.get('lastName', '')
print(firstName) //but this doesnt print "Peter" and "Becker"
print(lastName)
return("have a connection")
我不知道为什么Flask无法获得varibale firstName和lastName。我也尝试过
[firstName = request.args.get('firstName')
,然后我打印名字时,它打印null
我不知道这有什么问题,希望有人能帮助我。
谢谢
您可能需要使用request.get_json().get('firstName', '')
,因为这是一项POST
要求
我认为您实际上没有使用正确的方法在烧瓶代码中获取args。
检查此线程:Get the data received in a Flask request
您应该做的
@app.route("/addPerson", methods=["POST"])
def addPerson():
firstName = request.json.get('firstName', '')
lastName = request.json.get('lastName', '')
print(firstName) //but this doesnt print "Peter" and "Becker"
print(lastName)
return("have a connection")
此外,正如post方法的Axios文档所解释的,无需将您的身体传递到params对象内。您应该在React代码中或在flask代码中发出params对象。
lastName = request.json.get('params').get('lastName', '')