在这个例子中,是因为前端的表单了指定了method为get请求,而后端接收数据的method规定了需要post请求,故所以出现这个问题。
下面我们改造一下后端代码:
# coding: utf8
from flask import Flask, request
webapp = Flask(__name__)
@webapp.route('/ttropsstack', methods=['GET','POST'])
def ttropsstack():
if request.method == 'POST':
print request.get_data(as_text=True)
return 'ok'
else:
return '提交数据需要post请求'
if __name__ == '__main__':
webapp.run(host="0.0.0.0", port=8088, debug=True)
前端表单中的method还是保持get请求,再次提交,后端的返回如下:
看到了吗?后端判断前端过来的请求是get还是post,很显然,前端过来的请求是get,并且返回了非常友好的提示。
接下来我们继续改造一下前端的代码,将请求修改为post,代码如下:
<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8">
<title>彩虹运维技术栈社区主页</title>
</head>
<body>
<h2>彩虹运维技术栈社区,公众号ID:TtrOpsStack</h2>
<h3>主机信息</h3>
<form action="http://192.168.11.10:8088/ttropsstack" target="_blank" method="post">
<label for="ipaddr">IP地址</label>
<input type="text" id="ipaddr" name="ip"><br>
<input type="submit" value="提交">
</form>
</body>
</html>
后端代码也稍微改造一下,改变接收前端数据的方法
# coding: utf8
from flask import Flask, request
webapp = Flask(__name__)
@webapp.route('/ttropsstack', methods=['GET','POST'])
def ttropsstack():
if request.method == 'POST':
a = request.form
print a.get('ip')
print type(a)
return 'ok'
else:
return '提交数据需要post请求'
if __name__ == '__main__':
webapp.run(host="0.0.0.0", port=8088, debug=True)
输入IP地址,并点击提交
提交后,后端给前端返回了ok
接下来看下后端,后端啥也没做,就获取到表单的数据,然后打印了数据,并且打印了下数据类型