I implemented the server in Python's http.server as shown below, and I tried to POST the server using fetch API from the browser, but the browser is waiting for the response
.
Why?
If you look at the network situation using the browser development tool, it seems that the html and javascript files have been obtained, but POST seems to take a long time
python server.py:
import http.server
class MyHandler (http.server.BaseHTTPRequestHandler):
protocol_version = "HTTP/1.1"
def do_POST(self):
# Now this method just print path and content-type.
print("POSTED")
content_type=self.headers ["Content-Type"]
print(content_type)
print(self.path)
if "multipart/form-data" in content_type:
raw_data=self.rfile.read()
self.send_response(200,self.responses[200][0])
self.send_header("access-control-allow-origin", "*")
self.end_headers()
# WIP:do something...
def do_GET(self):
if self.path[0]=="/":
self.path = self.path [1:]
try:
with open(self.path, "rb") asf:
file_data=f.read()
except FileNotFoundError:
self.send_response(404, self.responses[404][0])
self.end_headers()
return
print(file_data)
content_length=len(file_data)
self.send_response(200,self.responses[200][0])
self.send_header("content-length", content_length)
self.end_headers()
self.wfile.write(file_data)
def parse_post():
# WIP
pass
httpd=http.server.HTTPServer(",6788), MyHandler)
print("Address:", "", "Port:", 6788)
httpd.serve_forever()
js code:
let myheaders=new Headers();
myheaders.append("content-type", "multipart/form-data");
let formdata = new FormData();
formdata.append("Hello", "World");
fetch("http://localhost:6788/nk", {
method: "POST",
mode: "cors",
body:formdata,
header —myheaders
}).then(response)=>response.text()) .then(text)=>console.log(text));
mode: "cors"
, because the browser sends a CORS-preflight request
, the server must process the OPTIONS
request in addition to the POST
and GET
requests.
© 2025 OneMinuteCode. All rights reserved.