node.js - 代理在 nginx 上传递 Socket.IO 连接不起作用
问题描述
我正在尝试使用 nginx 代理传递 node.js-socket.io 应用程序。
客户端是一个包含一些 javascript 的 html 文件;
<html>
<head>
<script src="socket.io.js"></script>
<script>
var socket = io('http://localhost:80');
socket.on('welcome', function(data){
console.log('Server says:' + data);
socket.emit('client-response', 'thank you!');
});
</script>
</head>
<body>
Socket.io
</body>
</html>
应该在 nginx.conf 文件中代理传递的服务器块是这样的;
server {
listen 80;
listen [::]:80;
#root /usr/share/nginx/html;
include /etc/nginx/default.d/*.conf;
location / {
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "Upgrade";
proxy_pass "http://localhost:2156";
}
error_page 404 /404.html;
location = /40x.html {
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
}
}
我的 node.js 应用程序在端口“2156”中启动并运行。
当我对此进行测试时,客户端尝试访问端口 80 上的 socket.io 并失败并出现 404 错误(因为 nginx 应该将代理传递到端口 2156 但它没有)。
我在这里想念什么?
解决方案
编辑:我已经将客户端更改为连接"http://localhost/socket.io/"
并重写了 nginx.conf,如下所示:
server {
listen 80 default_server;
listen [::]:80 default_server;
root /usr/share/nginx/html;
location /socket.io/ {
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "Upgrade";
proxy_set_header Host $host;
proxy_pass http://localhost:2156/socket.io/;
}
error_page 404 /404.html;
location = /40x.html {
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
}
}
它奏效了。
推荐阅读
- python - 如何将文本放在 print(count) 的末尾(Python)
- python - Python美汤/查找
- powershell - 无法在 jenkinsfile 的 powershell 步骤中打印定义的环境变量
- javascript - 使用 JSON 对象制作 html 表
- php - PHP foreach banlist 只检查文件的最后一行
- vue.js - Nuxt JS 中的全局组件
- sparql - 在 SPARQL 的子查询中聚合
- javascript - 我无法从 Poke API 访问我想要的对象
- php - 使用多个参数作为 Doctrine 的 SUBSTRING() 函数的参数
- c++ - 为什么连续的 istream_iter 对象会增加迭代流?