Python Tornado: how do I set WebSocket headers?
<p>I'm new to web development so let me explain:<br>
I want my Python Tornado server to communicate with a web page. My web page uses WebSockets and the <code>onmessage</code> function to print what it should receive from the Tornado server. Basically, here is the HTML JavaScript part:</p>

<pre class="lang-js prettyprint-override"><code>$(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()
</code></pre>

<p>I'm setting the <code>withCredentials</code> parameter to <code>true</code> so <a href="https://en.wikipedia.org/wiki/Cross-origin_resource_sharing" rel="nofollow">CORS</a> are enabled.</p>

<p>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 <code>Access-Control-Allow-Origin</code> enabled. Here is the tornado code:</p>

<pre class="lang-py prettyprint-override"><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()
</code></pre>

<p>I'm stuck with the following error in my browser!</p>

<pre class="lang-none prettyprint-override"><code>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).
</code></pre>

<p>What am I missing???</p>

<p>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. </p>

javascript python websocket cors tornado