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