所以过去几天我一直在处理这个问题,但仍然没有找到解决方案。我花了一些时间在 github 或 stackoverflow 上尝试了提到的方法,但仍然不起作用:
在进入问题之前,让我简单解释一下我当前的项目。
项目: 前端是reactjs,后端是Flask,后端由gunicorn 和nginx Web 服务器部署。
AWS 架构: Route53 -> Cloudfront ->(S3、EC2)。 S3 存储桶服务于前端(react 构建),EC2 服务于后端(API、websocket)。我已经有了自己的域名,并通过了 ACM 认证,并放置在 CloudFront 上。 我将 S3 和 EC2(2 个来源)放在云前端中,其中 S3 提供通过 HTTPS 加载的 Web 托管并向 EC2 发送请求。所以cloudfront和ec2之间的连接是通过HTTP进行的。
S3 的行为是默认 (*),EC2 的行为是 (/api)。该方法设置为 GET/POST/PUT...,我为请求启用了所有方法。当谈到 api request 部分时,一切都工作得很好,请求被正确处理并将响应发送回客户端。该问题仅发生在我收到此错误的 websocket 上:
获取 https://www.jungp.online/socket.io/?user_id=1&EIO=4&transport=polling&t=OtLZxOo 404(未找到)
用于连接 io 的前端反应
useEffect(() => {
const socket = io("https://www.jungp.online", {
path: '/socket.io',
query: {
user_id: Cookies.get("userId")
}
});
Nginx 配置:
map $http_upgrade $connection_upgrade {
default upgrade;
'' close;
}
server {
listen 80;
server_name www.jungp.online;
location / {
proxy_pass http://127.0.0.1:8080;
include /etc/nginx/proxy_params;
proxy_redirect off;
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_set_header X-Forwarded-Proto $scheme;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection $connection_upgrade;
}
location /socket.io {
proxy_pass http://127.0.0.1:8080/socket.io;
include /etc/nginx/proxy_params;
proxy_http_version 1.1;
proxy_buffering off;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection $connection_upgrade;
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_set_header X-Forwarded-Proto $scheme;
}
}
运行命令:
gunicorn -k geventwebsocket.gunicorn.workers.GeventWebSocketWorker -b 0.0.0.0:8080 wsgi:app
应用程序.py
app = Flask(__name__)
socketio = SocketIO(app, path='/socket.io', cors_allowed_origins="*")
CORS(app)
wsgi.py:
from app import socketio, app
if __name__ == "__main__":
socketio.run(app, host="0.0.0.0", port=8080)
非常感谢任何帮助,提前致谢。
好吧,经过几天的处理,我终于找到了解决方案。
解决方案相当简单,因为我的 ec2 和 s3 位于 CloudFront 后面,所以必须将 ec2 的行为配置为采用 socket.io 的路由路径。因此,只需将路径模式 /socket.io/* 添加到行为中即可。
希望这能帮助其他与我具有相同架构但遇到此问题的人。