Search code examples
javascriptpythonwebsocketcorstornado

Python Tornado: how do I set WebSocket headers?


I'm new to web development so let me explain:
I want my Python Tornado server to communicate with a web page. My web page uses WebSockets and the onmessage function to print what it should receive from the Tornado server. Basically, here is the HTML JavaScript part:

$(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.

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. 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???


Solution

  • Your javascript is using EventSource but your server is serving WebSockets. These are two completely different things. You need to change one of those to match the other.