简体   繁体   English

龙卷风,JavaScript,本地主机,空响应

[英]tornado, javascript, localhost, empty responce

I have a simple local tornado server with python code: 我有一个带有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()

and html-page: 和html页:

<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". 但是,如果我在浏览器中转到http://127.0.0.1:8888/?a=test ,则会显示文本“这是您的响应。测试”。

I tried to put javascript function into an external file, but the result is the same. 我试图将javascript函数放到一个外部文件中,但是结果是一样的。 Why I can't get answer through XMLHttpRequest and what should I do to get it? 为什么我无法通过XMLHttpRequest得到答案,应该怎么做?

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. 到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. 允许我与Chrome扩展程序中的龙卷风一起工作。 Actually, I don't understand exactly what it means. 其实,我不知道这到底意味着什么。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM