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

0

5

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?

Ramose answered 29/10, 2016 at 0:9 Comment(1)
Have you considered the possibility that this is a CORS red herring? Try adding self.send_header('Access-Control-Allow-Origin', '*'), self.send_header('Access-Control-Allow-Headers', 'Content-Type,Authorization'), self.send_header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE')Inly

© 2022 - 2024 — McMap. All rights reserved.