3

This is my first.py file.

from flask import Flask
from flask_socketio import SocketIO,send

app=Flask(__name__)

app.config['SECRET_KEY']='myscret'
socketio=SocketIO(app)

@socketio.on('message')
def handlemessage(msg):
    print('Message:'+msg)

    send(msg,broadcast=True) 


if __name__=='__main__':
    socketio.run(app,debug=True)

This is index.html file.

<html>
<head>
    <title>Chat room</title>
    <script type="text/javascript"  
src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/1.4.8/socket.io.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
</head>
<body>
    <script type="text/javascript" >
    $(document).ready(function()
    {
        var socket=io.connect('http://127.0.0.1:5000');
        socket.on('connect',function()
        {
            socket.send('User has connected');
        });

    });
    </script>

    <ul id="messages"></ul>

    <input type="text" id="myMessage">
    <button id="sendbtn">Send</button>
</body>

</html>

But when I run first.py file and open index.html in browser following error occurs.

Access to XMLHttpRequest at 'http://127.0.0.1:5000/socket.io/?EIO=3&transport=polling&t=N9J4bHD' from 
origin 'null' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on 
the requested resource.  index.html:1 

GET 127.0.0.1:5000/socket.io/?EIO=3&transport=polling&t=N9J4bHD:1 Failed to load resource: 
net::ERR_FAILED   socket.io.min.js:2

Access to XMLHttpRequest at 'http://127.0.0.1:5000/socket.io/? 
EIO=3&transport=polling&t=N9J4bQM' from origin 'null' has been blocked by CORS policy: No 'Access- 
Control-Allow-Origin' header is present on the requested resource.

127.0.0.1:5000/socket.io/?EIO=3&transport=polling&t=N9J4bQM:1 Failed to load resource: 
net::ERR_FAILED

Access to XMLHttpRequest at 'http://127.0.0.1:5000/socket.io/? 
EIO=3&transport=polling&t=N9J4c8L' from origin 'null' has been blocked by CORS policy: No 'Access- 
Control-Allow-Origin' header is present on the requested resource.

What should I do to solve this error? Please help.

Roshan Ojha
  • 111
  • 4
  • 13

2 Answers2

2

Please follow the steps:

  1. Install Flask-CORS module. Run the following command in terminal:
pip install -U flask-cors
  1. Import the module:
app=Flask(__name__)
from flask_cors import CORS
  1. Instantiate it:
CORS(app)
  1. Instantiate SocketIO like below:
socket = SocketIO(app, cors_allowed_origins="*")
  1. Use the socket decorator like below:
@socket.on('message')
def handlemessage(msg):

Note: Point #4, should be only considered for development phase. Even in the development phase, if you still want to narrow down the incoming requests, you can try: cors_allowed_origins='null', with your setup. But, I still don't recommend this in production. In this case, you can configure cors_allowed_origins accordingly with the hosted address.

ngShravil.py
  • 4,742
  • 3
  • 18
  • 30
  • This response is incorrect because the OP has a problem with Socket.IO, not with Flask routes. CORS configuration for Socket.IO is done directly in the Flask-SocketIO extension. – Miguel Grinberg May 26 '20 at 22:48
  • Thanks for letting me know @Miguel. I have updated my answer. Anyway, it will be helpful for the future reference, if the person uses the routes later. Let me know, if still any modifications are required. – ngShravil.py May 27 '20 at 04:39
  • Setting `cors_allowed_origins` to `'*'` is basically disabling the protections CORS give your server and allowing anyone to connect. Definitely not a good idea. – Miguel Grinberg May 27 '20 at 16:06
  • Thanks @Miguel, for your thoughts. That's absolutely correct. Well, I gave this idea, considering that the user's development is not blocked. Anyways, I have updated my answer. – ngShravil.py May 27 '20 at 20:05
  • Hey @RoshanOjha, is this helpful? – ngShravil.py May 30 '20 at 08:03
1

I assume you are running a quick test with this?

You seem to have a client file that you are opening directly from your file system, so it is not served by your web server. This file is trying to connect to the Socket.IO server. Web browsers do not allow connection across origins by default, so a connection from a locally hosted file (origin 'null') to your server (origin 'http://localhost:5000') is not possible unless you explicitly tell the Socket.IO server that you allow it.

You have a couple of possible solutions:

  • serve your HTML/CSS/JS files from your Flask web server. To do this, put them in the static folder of your Flask project and open them from their http://localhost:5000 address (for example, http://localhost:5000/static/index.html).

  • configure the cors_allowed_origins option of the Flask-SocketIO server to accept connections from the null origin.

Miguel Grinberg
  • 65,299
  • 14
  • 133
  • 152