Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CORS request did not succeed in python flask-socketio

I need help in debugging -the Same Origin Policy disallows reading the remote resource at https://some-domain.com. (Reason: CORS request did not succeed) in python flask-socketio error.

I am working on a chat application using python flask-socketio. In previously I have created that application in local and it works fine as expected, while I move the below code to the server it shows the above error. The client code runs in the https servers and server code also runs on the https server I don't know why that error shows.

I have attached my code below and please give a better solution to me.

server.py

    import json
    import os
    from flask import Flask, render_template, request,session
    from flask_socketio import SocketIO, send, emit
    from datetime import timedelta,datetime
    from flask_cors import CORS

    app = Flask(__name__)
    app.config['SECRET_KEY'] = 'secretkey'
    app.config['DEBUG'] = True
    app.config['CORS_HEADERS'] = 'Content-Type'
    cors = CORS(app, resources={r"/*": {"origins": "*"}})
    socketio = SocketIO(app)

    users = {}

    @app.before_request
    def make_session_permanent():
        session.permanent = True
        app.permanent_session_lifetime = timedelta(minutes=1)

    @app.route('/')
    #@cross_origin(origin='*',headers=['Content- Type','Authorization'])
    def index():
        return render_template('index.html')

    @socketio.on('connect')
    def connect():

        print("connected");
    @app.route('/orginate')
    def orginate():
        socketio.emit('server orginated', 'Something happened on the server!')
        return '<h1>Sent!</h1>'

    @socketio.on('username')
    def receive_username(username):
        users[username] = request.sid
        #users.append({username : request.sid})
        #print(users)
        emit('userList', users, broadcast=True)
        print('Username added!')
        print(users)
    if _name_ == '__main__':
        socketio.run(app,host='xxx.xxx.xx.x',port=5001)

client.js

var socket = io.connect("https://xxx.xxx.xx.x:5001/",{secure:false});

Screenshot 1: This screenshot explains the access-control-allow-orgin works fine for images under static folder in flask framework

enter image description here

Screenshot 2: This screenshot explains there is no access-control-orgin for socket call enter image description here

like image 792
VinothRaja Avatar asked Aug 20 '19 05:08

VinothRaja


1 Answers

You are using Flask-CORS to set up CORS on your Flask routes. You are missing a similar set up for Flask-SocketIO:

socketio = SocketIO(app, cors_allowed_origins=your_origins_here)

You can use '*' as the value to allow all origins (which I do not recommend), or set a single origin as a string, or a list of origins as a list of strings.

like image 193
Miguel Avatar answered Sep 24 '22 19:09

Miguel