websocket 跨域问题

服务端代码

.......
class WebSocketHandler(tornado.websocket.WebSocketHandler):
    def open(self):
        self.write_message('x') 
.......

客户端 为一段js

var wsUpdater = {
    socket: null,
    start: function(){
        if ("WebSocket" in window) {
            wsUpdater.socket = new WebSocket("ws://xx/websocket");
        } 
        else {
            wsUpdater.socket = new MozWebSocket("ws://xx/websocket");
        }
        wsUpdater.socket.onmessage = function(event) {
            document.write(event.data)
        };
    }
};
wsUpdater.start(); 

场景是在任意网站加载这段js代码,

显示430
Cross origin websockets not allowed

我百度的资料上说websocket 可以跨域啊。为什么会这样? 如何解决呢?还望指点一二

阅读 10.4k
评论
    2 个回答
    • 4.9k

    Tornado 4.0 可以重写 check_origin 方法

    class WebSocketHandler(tornado.websocket.WebSocketHandler):
    
        def check_origin(self, origin):
            return True
    
        def open(self):
            self.write_message('x') 
    

    或者指定允许的域名

    def check_origin(self, origin):
        parsed_origin = urllib.parse.urlparse(origin)
        return parsed_origin.netloc.endswith(".mydomain.com")
    

    tornado 3.0 没有提供类似的方法,可以重写 header

    class WebSocketHandler(tornado.websocket.WebSocketHandler):
    
        def set_default_headers(self):
            self.set_header('Access-Control-Allow-Origin', '*')
            self.set_header('Access-Control-Allow-Methods', 'POST, GET, OPTIONS')
            self.set_header('Access-Control-Max-Age', 1000)
            self.set_header('Access-Control-Allow-Headers', '*')
          # self.set_header('Content-type', 'application/json')
    
        def open(self):
            self.write_message('x') 
    
    

    文档 check_origin

      • 4
      • 新人请关照

      握手后在头里加access-control-allow-origin:*

        撰写回答

        登录后参与交流、获取后续更新提醒