0

I have a simple local tornado server with python code:

import tornado.ioloop
import tornado.web

from tornado.options import define, options, parse_command_line

define("port", default=8888, help="run on the given port", type=int)

class MainHandler(tornado.web.RequestHandler):
    @tornado.web.asynchronous
    def get(self):
        self.write("This is your response. " + self.get_argument("a", "hi"))
        self.finish()

app = tornado.web.Application([
    (r'/', MainHandler),
])

if __name__ == '__main__':
    parse_command_line()
    app.listen(options.port)
    tornado.ioloop.IOLoop.instance().start()

and html-page:

<html>
<head>
<script type="text/javascript">
function confirmGetMessage() {

    var xhr = new XMLHttpRequest();
    xhr.open("GET", "http://127.0.0.1:8888/?a=mytest", true);
    xhr.onreadystatechange = function() {
        alert("resp text = " + xhr.responseText);   
        alert("state = " + xhr.readyState);
        alert("status = " + xhr.status);
    }
    xhr.send(); 

}
</script>
</head>
<body>
<form>
<input type="button" onclick="confirmGetMessage()" value="Click me for some reason" />
</form>
</body>
</html>

If I open this page in the browser and press the button, the result is:

resp text =
state = 4
status = 0

But if I go to http://127.0.0.1:8888/?a=test in the browser, I have a text "This is your response. test".

I tried to put javascript function into an external file, but the result is the same. Why I can't get answer through XMLHttpRequest and what should I do to get it?

  • Possible duplicate of [Empty responseText from XMLHttpRequest](http://stackoverflow.com/questions/1941340/empty-responsetext-from-xmlhttprequest) – Ben Darnell Nov 01 '15 at 18:27

1 Answers1

0

I added

def set_default_headers(self):
    self.add_header('Access-Control-Allow-Origin', self.request.headers.get('Origin', '*'))

    self.add_header('Access-Control-Request-Method', 'POST')

to MainHandler.

self.add_header('Access-Control-Request-Method', 'POST')

resolved this problen and

self.add_header('Access-Control-Allow-Origin', self.request.headers.get('Origin', '*'))

allowed me to work with tornado from chrome extension. Actually, I don't understand exactly what it means.