我是网络开发的新手,所以让我解释一下:
我希望我的Python Tornado服务器与网页进行通信。我的网页使用WebSockets和onmessage
函数来打印它应该从Tornado服务器接收的内容。基本上,这是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()
我将withCredentials
参数设置为true
,因此启用了CORS。
在Tornado方面,我有一个WebSocket类应该回复,但我不知道如何设置标题以启用Access-Control-Allow-Origin
。这是龙卷风代码:
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()
我在浏览器中遇到以下错误!
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).
我缺少什么?
答案 0 :(得分:2)
您的javascript正在使用EventSource,但您的服务器正在为WebSockets提供服务。这是两件完全不同的事情。您需要更改其中一个以匹配另一个。