Chrome 中 flask-socket.io 的 CORS 错误

CORS error with flask-socket.io in Chrome

所以我正在尝试使用 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": ""}})

有人遇到过此类问题吗?

很快,

我们有 "disable web security" 命令行选项 运行 Chrome...

--disable-web-security

此外,我们可以在服务于 api...

的服务器上启用 CORS
Access-Control-Allow-Origin: * 

您的客户端正在尝试连接到 URL https://socket.io/,您可以在 CORS 错误消息中看到这一点。

这不是您的 Socket.IO 服务器的 URL,它实际上是官方 Socket.IO 网站。您需要改进客户端中的逻辑,以便为您的服务使用正确的连接 URL,您在此处所做的操作不适用于本地 HTML 文件:

var socket = io.connect('http://' + document.domain + ':' + location.port);

尝试硬编码您的服务器地址:

var socket = io.connect('http://localhost:5002');