javascript client to Python server: XMLHttpRequest responseText is empty after Get request

佐手、 提交于 2021-02-20 18:50:12

问题


I am trying to write a chrome extension which is able to send/receive data to/from a python server script. Currently, I am at the point where the js script is making a GET request okay, the only issue being that the .responseText is always empty (even though the python script is responding with text).

popup.js

document.addEventListener('DOMContentLoaded', function() {  
    var xhr = new XMLHttpRequest();

    xhr.onreadystatechange = function() {
        if (xhr.readyState == xhr.DONE) {           
            var resptxt = xhr.responseText;

            if (resptxt) {
                document.getElementById('texthtm').innerHTML = resptxt;
            } else {
                document.getElementById('texthtm').innerHTML = "no response";
            }
        }
    }

    xhr.open("GET", "http://127.0.0.1:80", true);
    xhr.send();
});

server.py

import time
import BaseHTTPServer
from SimpleHTTPServer import SimpleHTTPRequestHandler

HOST_NAME = "127.0.0.1" 
PORT_NUMBER = 80 

class MyHandler(BaseHTTPServer.BaseHTTPRequestHandler):
    def do_HEAD(self):
        self.send_response(200)
        self.send_header("Content-type", "text/plain")
        self.end_headers()
    def do_GET(self):
        self.send_response(200)
        self.send_header("Content-type", "text/plain")
        self.end_headers()
        self.wfile.write("heyyy")


if __name__ == "__main__":

    server_class = BaseHTTPServer.HTTPServer
    httpd = server_class((HOST_NAME, PORT_NUMBER), MyHandler)
    print time.asctime(), "Server Starts - %s:%s" % (HOST_NAME, PORT_NUMBER)

    try:
            httpd.serve_forever()
    except KeyboardInterrupt:
            pass

    httpd.server_close()
    print time.asctime(), "Server Stops - %s:%s" % (HOST_NAME, PORT_NUMBER)

So every time I press the extension button, it just displays "no response", which means that the request is at least being done. What am I doing wrong here?

来源:https://stackoverflow.com/questions/40314747/javascript-client-to-python-server-xmlhttprequest-responsetext-is-empty-after-g

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!