Chrome中flask-socket.io的CORS错误

问题描述 投票:0回答:1

所以我试图使用flask-socket.io构建一个基本的聊天应用程序,但是遇到一些奇怪的错误。

服务器

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>

当我从http://localhost:5002/访问它时,该应用程序运行良好,但是如果我在本地加载html文件,则会出现此错误

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.

我尝试按照其他地方的建议将cors_allowed_origins = []和cors_allowed_origins =“ *”添加到服务器,但是它没有任何改变。奇怪的是,它可以在Internet Explorer中工作,但不能在chrome中工作。

我也尝试添加CORS(app,resources = {r“ / ”:{“ origins”:“”}})]

任何人都有处理此类问题的经验吗?

javascript flask socket.io cors flask-socketio
1个回答
0
投票

很快,

我们具有用于运行Chrome浏览器的“禁用网络安全”命令行选项...

--disable-web-security

此外,我们可以在服务API的服务器上启用CORS ...

Access-Control-Allow-Origin: * 
© www.soinside.com 2019 - 2024. All rights reserved.