【发布时间】:2021-08-05 16:12:19
【问题描述】:
我正在尝试创建一个与 React 客户端(端口 3000)有 socket.io 连接的 Flask 服务器(端口 5000)。当我尝试执行服务器脚本(如下所示)时,即使我使用的是 CORS,我也会收到一条错误消息“http://localhost:3000 is not an accepted origin”。
服务器测试.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 -
【问题讨论】:
标签: reactjs flask websocket socket.io cors