简体   繁体   English

Python Tornado:如何设置WebSocket标头?

[英]Python Tornado: how do I set WebSocket headers?

I'm new to web development so let me explain: 我是Web开发的新手,所以让我解释一下:
I want my Python Tornado server to communicate with a web page. 我希望我的Python Tornado服务器与网页进行通信。 My web page uses WebSockets and the onmessage function to print what it should receive from the Tornado server. 我的网页使用WebSockets和onmessage函数打印应从Tornado服务器接收的内容。 Basically, here is the HTML JavaScript part: 基本上,这是HTML JavaScript部分:

$(document).ready(function() {

    var myURL = "http://localhost:8888";
    var source = new EventSource(myURL, { withCredentials: true }); // Access-Control-Allow-Origin
    ...
    source.onmessage = function(event) {
      console.log("received new event!");
    };
    ...
}); // ready()

I'm setting the withCredentials parameter to true so CORS are enabled. 我将withCredentials参数设置为true以便启用了CORS

On the Tornado side, I have a WebSocket class which is supposed to answer back, but I don't know how to set the header to have Access-Control-Allow-Origin enabled. 在“龙卷风”方面,我有一个WebSocket类,应该对它进行回答,但我不知道如何设置标题以启用Access-Control-Allow-Origin Here is the tornado code: 这是龙卷风代码:

class EchoWebSocket(tornado.websocket.WebSocketHandler):

  def check_origin(self, origin):
     return True

  def on_message(self, message):
    self.write_message(u"Received message: " + message)

def make_app():
  return tornado.web.Application([ ('/', EchoWebSocket), ])

if __name__ == '__main__':
  app = make_app()
  app.listen(8888)
  print 'listening on port 8888...'
  # start main loop
  tornado.ioloop.IOLoop.current().start()

I'm stuck with the following error in my browser! 我在浏览器中遇到以下错误!

GET http://localhost:8888/ [HTTP/1.1 400 Bad Request 1ms]
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:8888/. (Reason: CORS header 'Access-Control-Allow-Origin' missing).

What am I missing??? 我在想什么???

Your javascript is using EventSource but your server is serving WebSockets. 您的JavaScript使用的是EventSource,但您的服务器正在提供WebSockets。 These are two completely different things. 这是两件完全不同的事情。 You need to change one of those to match the other. 您需要更改其中一个以匹配另一个。

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

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