龙卷风,javascript,localhost,空响应

时间:2015-11-01 18:18:27

标签: javascript xmlhttprequest localhost tornado

我有一个带有python代码的简单本地龙卷风服务器:

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()

和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>

如果我在浏览器中打开此页面并按下按钮,结果为:

resp text =
state = 4
status = 0

但如果我在浏览器中转到http://127.0.0.1:8888/?a=test,我会收到一条文字&#34;这是您的回复。测试&#34;

我试图将javascript函数放入外部文件,但结果是一样的。 为什么我无法通过XMLHttpRequest获得答案,我该怎么做才能获得答案?

1 个答案:

答案 0 :(得分:0)

我添加了

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')

到MainHandler。

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

解决了这个问题和

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

允许我使用chrome扩展中的龙卷风。 实际上,我并不完全明白这意味着什么。