No response (status, responseText) is coming back from python httpserver "example" to javasacript request. javasacript request seems to be okay, but it is not getting from HTTP server "example". Any advice would be much appreciated.
XML HTTP Request in Javascript
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
x = this.responseText
}
xhr.open('GET', 'http://127.0.0.1:8080/example', true);
xhr.send();
HTTP Server "example" in Python
from http.server import BaseHTTPRequestHandler, HTTPServer
hostName = "localhost"
serverPort = 8080
class MyServer(BaseHTTPRequestHandler):
def do_GET(self):
self.send_response(200)
#self.send_response(status.code, status.message)
self.send_header("Content-type", "text/html")
self.end_headers()
self.wfile.write(bytes("<html><head><title>https://pythonbasics.org</title></head>", "utf-8"))
self.wfile.write(bytes("<p>GET: %s</p>" % self.path, "utf-8"))
self.wfile.write(bytes("<body>", "utf-8"))
self.wfile.write(bytes("<p>This is do_GET of HTTP server.</p>", "utf-8"))
self.wfile.write(bytes("</body></html>", "utf-8"))
self.wfile.close()
#self.wfile.write(bytes("Hello, world!", "utf-8"))
def do_POST(self):
# read the content-length header
content_length = int(self.headers.get("Content-Length"))
# read that many bytes from the body of the request
body = self.rfile.read(content_length)
self.send_response(200)
self.end_headers()
self.wfile.write(body)
if __name__ == "__main__":
webServer = HTTPServer((hostName, serverPort), MyServer)
print("Server started http://%s:%s" % (hostName, serverPort))
I got the answer from Enable access control on simple HTTP server: The line self.send_header("Access-Control-Allow-Origin", "*") resolved my problem as below: