我正在尝试开发将具有Python Web服务器的应用程序。一切都按预期工作,但是在执行逻辑(通过使用do_GET和do_POST方法)之后,服务器仅停止运行,并且显示连接重置页面。下面是页面的屏幕截图:
下面是Python网络服务器代码:
from http.server import BaseHTTPRequestHandler, HTTPServer
# HTTPRequestHandler class
class testHTTPServer_RequestHandler(BaseHTTPRequestHandler):
# GET
def do_GET(self):
# Send response status code
self.send_response(200)
# Send headers
self.send_header('Content-type','text/html')
self.end_headers()
file = "./some2.html"
file2 = open(file,"r")
# Write content as utf-8 data
self.wfile.write(bytes(file2.read(), "utf8"))
#return
def do_POST(self):
content_len = int(self.headers.get('content-length', 0))
post_body = self.rfile.read(content_len)
print(post_body)
with open("rsmsg.txt","a") as f:
f.write(str(post_body))
print("Done storing file")
#return
def run():
print('starting server...')
# Server settings
server_address = ('192.168.10.151', 8083)
httpd = HTTPServer(server_address, testHTTPServer_RequestHandler)
print('running server...')
httpd.serve_forever()
run()
下面是HTML代码:
<html>
<body>
<script>
function getvalue(){
value1 = document.getElementById("first").innerHTML
value2 = document.getElementById("last").innerHTML
return value1+value2
}
</script>
<form action="" method="post">
First name:<br>
<input id="first" type="text" name="firstname">
<br>
Last name:<br>
<input id = "last" type="text" name="lastname">
<br><br>
<button type = "submit" onclick=getvalue()>Press it to store data on server</button>
</form>
</body>
</html>
按下按钮后,input id="first"
和input id="last"
中的数据将提供给服务器。但是按了为什么会显示重置连接页后,为什么?以及如何预防呢?
更新
调试后,我了解到在HTML代码的JS中,value1
和value2
为空,但是我仍然在获取数据!但带有字段名称。例:
firstname = Nick&lastname = A。我认为这可能是连接重置页面因此更新了问题的原因。