So I'm trying to build a basic chat app using flask-socket.io but am running into some strange errors.
Server
from flask import Flask, render_template
from flask_socketio import SocketIO
app = Flask(__name__)
app.config['SECRET_KEY'] = 'vnkdjnfjknfl1232#'
socketio = SocketIO(app, cors_allowed_origins="*")
@app.route('/')
def sessions():
return render_template('session.html')
def messageReceived(methods=['GET', 'POST']):
print('message was received!!!')
@socketio.on('my event')
def handle_my_custom_event(json, methods=['GET', 'POST']):
print('received my event: ' + str(json))
socketio.emit('my response', json, callback=messageReceived)
if __name__ == '__main__':
socketio.run(app, debug=True, port=5002)
Session.html
<!DOCTYPE html>
<html lang="en">
<head>
<title>Flask_Chat_App</title>
</head>
<body>
<h3 style='color: #ccc;font-size: 30px;'>No message yet..</h3>
<div class="message_holder"></div>
<form action="" method="POST">
<input type="text" class="username" placeholder="User Name"/>
<input type="text" class="message" placeholder="Messages"/>
<input type="submit"/>
</form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/1.7.3/socket.io.min.js"></script>
<script type="text/javascript">
var socket = io.connect('http://' + document.domain + ':' + location.port);
socket.on( 'connect', function() {
socket.emit( 'my event', {
data: 'User Connected'
} )
var form = $( 'form' ).on( 'submit', function( e ) {
e.preventDefault()
let user_name = $( 'input.username' ).val()
let user_input = $( 'input.message' ).val()
socket.emit( 'my event', {
user_name : user_name,
message : user_input
} )
$( 'input.message' ).val( '' ).focus()
} )
} )
socket.on( 'my response', function( msg ) {
console.log( msg )
if( typeof msg.user_name !== 'undefined' ) {
$( 'h3' ).remove()
$( 'div.message_holder' ).append( '<div><b style="color: #000">'+msg.user_name+'</b> '+msg.message+'</div>' )
}
})
</script>
</body>
</html>
The app works fine when I access it from http://localhost:5002/ but if I load the html file locally I get this error
Access to XMLHttpRequest at 'https://socket.io/?EIO=3&transport=polling&t=MyIHMvN' (redirected from 'http://socket.io/?EIO=3&transport=polling&t=MyIHMvN') from origin 'null' has been blocked by CORS policy: The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'. The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute.
I've tried adding cors_allowed_origins=[] and cors_allowed_origins="*" to the server as suggested in other places but it doesn't change anything. The strange thing is that it works in internet explorer but not in chrome.
I've also tried adding CORS(app, resources={r"/": {"origins": ""}})
Anyone have any experience with this sort of issue?