1

Hiyo,

I've setup a Python server with a GET request which seems to work, but for some reason I can't send anything back to the requesting client, which is coded in Javascript.

Python Server:

import time
import BaseHTTPServer


HOST_NAME = 'localhost'
PORT_NUMBER = 8000 


class MyHandler(BaseHTTPServer.BaseHTTPRequestHandler):
    def do_HEAD(s):
        s.send_response(200)
        s.send_header("Content-type", "text/html")
        s.end_headers()

    def do_GET(s):
        print "here i am, in python" #this prints, so i know i'm in here

        """Respond to a GET request."""
        s.send_response(200)
        s.send_header("Content-type", "application/json")
        s.send_header("Access-Control-Allow-Origin", "*")
        s.send_header("Access-Control-Expose-Headers", "Access-Control-Allow-Origin")
        s.send_header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept")
        s.end_headers()
        s.wfile.write("test1")
        return "test2"

        # If someone went to "http://something.somewhere.net/foo/bar/",
        # then s.path equals "/foo/bar/".
        s.wfile.write("<p>You accessed path: %s</p>" % s.path)
        s.wfile.write("</body></html>")


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)

Javascript Client:

$.ajax({
    method: "GET",
    url: "http://localhost:8000",
    success:function(result){
        console.log("success"); //does not print
        console.log(result);   //does not print
    },
    failure:function(err){
        console.log("couldn't make it"); //does not print
    }
});

So what I want is to send a GET request from JS to Py, and get some feedback from the server. Alas, nothing prints anywhere except for "here i am, in python", which suggests I'm in the server's GET code, but nothing gets sent back.

any ideas?

Thanks!

UPDATE

Ok, after tweaking with eton's suggestion, I have "success" printing from the success function.

the result parameter is also being printed, however, it is empty.

the do_GET now looks like this:

    def do_GET(s):
        print "here i am, in python"
#       """Respond to a GET request.""" 
        s.send_response(200)
        s.wfile.write("test1") 
        s.send_header("Content-type", "text/html")
        # s.send_header("Content-type", "application/json") 
        s.send_header("Access-Control-Allow-Origin", "*") 
        s.send_header("Access-Control-Expose-Headers", "Access-Control-Allow-Origin") 
        s.send_header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept") 
        s.end_headers() 

Maybe I'm returning it wrong? I have no idea. Been reading the docs and other posts but to no avail so far.

Thanks again

Jona
  • 1,023
  • 2
  • 15
  • 39
  • Have you checked the raw request/response in your browser's inspector's network tab...? – deceze Apr 20 '16 at 09:46
  • You should place your s.send_response(200) after your s.wfile.write statements – eton_ceb Apr 20 '16 at 09:50
  • @eton_ceb ok i tried that, and now i'm getting a cross-origin error (`No 'Access-Control-Allow-Origin'`), despite all the mumbo-jumbo to prevent that above =/ – Jona Apr 20 '16 at 09:52
  • @deceze not exactly sure what you mean; i see a few GETs but none from the server – Jona Apr 20 '16 at 10:08
  • @Jona, oh sorry, I was testing by serving on localhost, and triggering the ajax call from the chrome web inspector console thus not reproducing CORS-related problems – eton_ceb Apr 20 '16 at 10:22
  • @Jona, regarding to CORS-related issue, you might want to test solutions posted here: http://stackoverflow.com/questions/16583827/cors-with-python-basehttpserver-501-unsupported-method-options-in-chrome – eton_ceb Apr 20 '16 at 10:39
  • @eton_ceb hmm, thanks. looking into it but no magic solutions yet – Jona Apr 20 '16 at 10:55
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/109661/discussion-between-eton-ceb-and-jona). – eton_ceb Apr 20 '16 at 11:16

1 Answers1

0

Actually, with this code the JS client will wait indefinitely for a response. You need to set Content-length header to tell the JS client when it should stop waiting for more bytes.

In your case, this translates to this:

self.send_header("Content-Length", str(len('test1')))
Fethi Dilmi
  • 161
  • 3
  • 16