From origin 'null' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource

Viewed 4293

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.

2 Answers

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.

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.

Related