我的情况是服务端用Flask,前端用Vue.js。问题都出在Flask上。
CORS跨域问题
这个问题令我很不愉快,是因为写法的问题导致的。实际上我在实例化SocketIO时已经传入cors_allowed_origins的参数为*,但是最后的问题出在*要用单引号,不能用双引号。我觉得这可能是前后传参符号不一致导致的,应该不是必须要求写单引号。
# 错误的写法socketio = SocketIO(app, cors_allowed_origins="*", async_mode='eventlet')# 正确的写法socketio = SocketIO(app, cors_allowed_origins='*', async_mode='eventlet')
400错误
这个需要配置Nginx,参考了一篇帖子,配置如下
location /{ proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade";}
其中第一行是告诉nginx使用HTTP/1.1通信协议,这是websoket必须要使用的协议。
第二行和第三行告诉nginx,当它想要使用WebSocket时,响应http升级请求。
参考资料:
- 400错误解决方法
- 400错误官方issue