我正在使用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.实际上,我正在使用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.py:
import eventlet
from myapp import create_app
eventlet.monkey_patch()
app, celery = create_app('config_prod.py')我也在我的应用工厂中使用CORS(应用程序)。
我还尝试在我的一个蓝图中添加以下内容:
@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我使用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;
}怎么了?谢谢!
发布于 2020-04-17 04:04:59
我在React Flask-SocketIO上遇到了类似的400问题,这个问题是由于CORS错误造成的。flask中的以下代码修复了我的问题,
socketio = SocketIO(app)
socketio.init_app(app, cors_allowed_origins="*")此外,当您选择仅[websocket]传输时,请确保您在服务器中使用eventlet或gevent-websocket。Gevent不支持websocket,因此只能与HTTP轮询回退一起使用。
发布于 2019-03-04 21:32:58
问题是我使用http而不是https添加原始主机。一切都很正常。
https://stackoverflow.com/questions/54967708
复制相似问题