先說一下接收方法,再說一下其中的大大大大大坑
1.get請求
前端代碼:
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8">
</head>
<body>
<form action="http://127.0.0.1:5000/test1" method="get">
姓名:<input type="text" name="name" value="caosong">
年齡:<input type="text" name="age" value=24>
<input type="submit" value="提交">
</form>
</body>
</html>
後臺代碼:
@app.route('/test1/',methods=["GET","POST"])
def test1():
print("name:")
print(request.args.get("name"))
print("all:")
print(json.dumps(request.args))
return json.dumps(request.args)
2.post請求
前端代碼:
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8">
</head>
<body>
<form action="http://127.0.0.1:5000/test1" method="post">
姓名:<input type="text" name="name" value="caosong">
年齡:<input type="text" name="age" value=24>
<input type="submit" value="提交">
</form>
</body>
</html>
後臺代碼:
@app.route('/test1',methods=["GET","POST"])
def test1():
print("name:")
print(request.form.get('name'))
print(""nameList:)
print(request.form.getlist('name'))
print("age:")
print(request.form.get('age', default='-1'))
return json.dumps(request.form)
3.最重要的大坑來了
細心的同學可能會發現上述代碼的細微差別,那就是下面的不同。
沒有錯,這個就是坑了我好久的問題,左側的是get請求,右側是post請求。一個url是'/test1/',一個url是'/test1'。
經過反覆實驗發現,get請求會在你的表單的action後面加上 /?等等 (無論有沒有參數),這也就造成了將後端的get改成post怎麼改都不好使的重要原因。
希望對小夥伴們有幫助。當然能贊更好了。
4.建議
建議把所有的URL都定義爲"/xxxxx/"這樣的形式,無論post,get就都ok了。
注意:是前後端都這麼寫