在 Flask 插座应用程序上连接时出错



我有一个Flask socket.io 应用程序(后端(托管在Heroku上。

我有带有JS代码的前端,可以连接到本地计算机上的主机。 我在尝试连接到服务器时收到以下错误。

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://deploy-appp.herokuapp.com/socket.io/?
EIO=3&transport=polling&t=MH05dP-. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing).
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://deploy-appp.herokuapp.com/socket.io/?
EIO=3&transport=polling&t=MH05f5A. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing).

链接到后端应用程序

用于套接字连接的JS代码:

<script type="text/javascript">
var socket = io.connect('https://deploy-appp.herokuapp.com/');
socket.on('connect', function() {
console.log('connected');
});
socket.on('message', function(msg) {
document.getElementById('messages').append('<li>'+msg+'</li>');
console.log('Received message');
});
function send() {
console.log(document.getElementById('myMessage').value)
socket.send(document.getElementById('myMessage').value)
};
</script>

查看 cors wiki .通常,如果您的前端应用程序从不同的 uri "运行"到后端,则会收到这样的错误。例如,客户端代码的主机是 myclient.com,但您的 socket.io 后端在 anotherclient.com 上运行。

对此有很多解决方案,您可以显式设置源,请参阅此答案 Socket.io + Node.js跨源请求被阻止。(如果您在本地运行 Web 应用程序,这是最快的,但长期不安全(

或者,在您的客户端 Web 服务器和 socketio 应用程序前面有一个反向代理,其中代理会将客户端/socketio 调用路由到您的 socketio 服务器,并将另一个请求路由到托管您站点的服务器。

最新更新