React 和 Flask Socket.IO - CORS 问题

React and Flask with Socket.IO - CORS problem

我正在尝试创建一个 Flask 服务器(端口 5000),它与 React 客户端 有一个 socket.io 连接](端口 3000)。当我尝试执行服务器脚本(如下所示)时,我收到一条错误消息“http://localhost:3000 is not an accepted origin”,即使我使用的是 CORS。

服务器-test.py:

from flask import Flask
from flask_socketio import SocketIO, emit
from flask_cors import CORS, cross_origin

import os
from dotenv import load_dotenv, find_dotenv
load_dotenv(find_dotenv())

app = Flask(__name__)
app.config['CORS_HEADERS'] = 'Content-Type'
app.config['SECRET_KEY'] = os.environ.get('SECRET')
socketio = SocketIO(app)
CORS(app)

@socketio.on('connect')
@cross_origin()
def handle_connection():
  emit('server-client', 'Test message')


@socketio.on('client-server')
@cross_origin()
def handle_client_msg(msg):
  print("\n" + str(msg))


if __name__ == '__main__':
  app.run(host="localhost", port=os.environ.get('PORT'))
  socketio.run(app)

App.jsx:

import { io } from 'socket.io-client';

// ...

useEffect(() => {
  const socket = io('http://localhost:5000');

  socket.on('server-client', msg => {
    alert(msg);
    socket.emit('client-server', 'Client: Message received!');
  });
}, []);

WSL 终端中的错误消息:

 * Serving Flask app 'server-test' (lazy loading)
 * Environment: production
   WARNING: This is a development server. Do not use it in a production deployment.
   Use a production WSGI server instead.
 * Debug mode: off
 * Running on http://localhost:5000/ (Press CTRL+C to quit)
http://localhost:3000 is not an accepted origin. (further occurrences of this error will be logged with level INFO)
127.0.0.1 - - [16/May/2021 00:27:31] "GET /socket.io/?EIO=4&transport=polling&t=NboMpZQ HTTP/1.1" 400 -
127.0.0.1 - - [16/May/2021 00:27:31] "GET /socket.io/?EIO=4&transport=polling&t=NboMpZS HTTP/1.1" 400 -
127.0.0.1 - - [16/May/2021 00:27:31] "GET /socket.io/?EIO=4&transport=polling&t=NboMpZR.0 HTTP/1.1" 400 -
127.0.0.1 - - [16/May/2021 00:27:31] "GET /socket.io/?EIO=4&transport=polling&t=NboMpZR HTTP/1.1" 400 -

The Flask SocketIO documentation 是这样说的:

If an incoming HTTP or WebSocket request includes the Origin header, this header must match the scheme and host of the connection URL. In case of a mismatch, a 400 status code response is returned and the connection is rejected.

还有这个:

If necessary, the cors_allowed_origins option can be used to allow other origins. This argument can be set to a string to set a single allowed origin, or to a list to allow multiple origins. A special value of '*' can be used to instruct the server to allow all origins, but this should be done with care, as this could make the server vulnerable to Cross-Site Request Forgery (CSRF) attacks.

所以不是这个:

socketio = SocketIO(app)

你可以这样做:

socketio = SocketIO(app, cors_allowed_origins="*")

与 cors 问题无关,但我还在函数中添加了 return 语句。没有 return 我得到的东西:

TypeError: The view function did not return a valid response.

如果使用 @cross_origin() 装饰器,似乎是必需的,因此您也可以删除它们,然后就不需要 return 语句。