【发布时间】:2016-08-26 19:19:00
【问题描述】:
我是网络开发的新手,所以让我解释一下:
我希望我的 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).
我错过了什么???
【问题讨论】:
标签: javascript python websocket cors tornado