Flask-SocketIO 和 400 错误请求

mag*_*noz 2 python flask socket.io flask-socketio

我正在使用 socketio 运行 Flask 应用程序来处理通知。Flask 应用程序正在侦听端口 5000,而客户端在 8080。

js 客户端总是收到这个错误:

VM15520:1 GET http://localhost:5000/socket.io/?EIO=3&transport=polling&t=Mb2_LpO 400 (Bad Request)
Access to XMLHttpRequest at 'http://localhost:5000/socket.io/?EIO=3&transport=polling&t=Mb2_LpO' from origin 'http://localhost:8080' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
Run Code Online (Sandbox Code Playgroud)

我实际上是用 gunicorn 启动我的应用程序的,如下所示:

gunicorn --workers=1 --worker-class eventlet --certfile=keys/key.crt --keyfile=keys/key.key --bind 0.0.0.0:5000 myapp.run:app
Run Code Online (Sandbox Code Playgroud)

这是我的 run.py:

import eventlet
from myapp import create_app
eventlet.monkey_patch()
app, celery = create_app('config_prod.py')
Run Code Online (Sandbox Code Playgroud)

我也在我的应用工厂中使用 CORS(app)。

我还尝试将其添加到我的一张蓝图中:

@api.after_request
def after_request(response):
    response.headers.add('Access-Control-Allow-Origin', 'http://localhost:8080')
    response.headers.add('Access-Control-Allow-Headers',
                         'Origin, X-Requested-With, Content-Type, Accept, Authorization')
    response.headers.add('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS')
    response.headers.add('Access-Control-Allow-Credentials', 'false')
    return response
Run Code Online (Sandbox Code Playgroud)

我使用 nginx 作为反向代理,因此我尝试添加我在flask-socketio 的文档中看到的相应配置:

location /socket.io {
    proxy_set_header Host $host;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;

    proxy_http_version 1.1;
    proxy_buffering off;
    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header Connection "Upgrade";
    proxy_pass https://my_backend_host/socket.io;
}
Run Code Online (Sandbox Code Playgroud)

怎么了?谢谢!

Saj*_*ier 13

我在 React Flask-SocketIO 上遇到了类似的 400 问题,这个问题是由于 CORS 错误造成的。烧瓶中的以下代码解决了我的问题,

socketio = SocketIO(app)
socketio.init_app(app, cors_allowed_origins="*")
Run Code Online (Sandbox Code Playgroud)

当您只选择传输时,还要确保您正在使用eventletgevent-websocket在您的服务器中[websocket]Gevent没有 websocket 支持,所以只适用于 HTTP 轮询回退。


mag*_*noz 4

问题是我添加原始主机http而不是https. 一切正常。

  • 谢谢,我刚刚收到此错误,将此行添加到 nginx 配置以删除 Origin 标头: proxy_set_header Origin ""; (4认同)