【发布时间】:2021-03-10 05:19:22
【问题描述】:
我正在尝试将我的 Angular 项目放在 prod 上,但套接字无法正常工作。在本地主机上一切正常,但是当我在我的服务器(Ubuntu 20.04)上启动它时,网站启动但在 chrome 控制台中我有一个关于套接字的 ERR_CONNECTION_TIMED_OUT。我不知道问题出在哪里。也许我需要从 localhost 编辑到我的服务器 ip 的 nginx conf 或链接。
[客户]
module.ts
import { SocketIoModule, SocketIoConfig } from 'ngx-socket-io';
const socketConfig: SocketIoConfig = { url: 'http://<server_ip>:3000', options: {} };
@NgModule({
declarations: [...],
imports: [
...
SocketIoModule.forRoot(socketConfig),
...
],
providers: [...],
bootstrap: [AppComponent]
})
export class AppModule {}
[服务器]
app.ts
const expressPort = 8080;
const _app = express();
_app.use(json({limit: '5mb'}));
_app.use(urlencoded({extended: true}));
_app.use(cors());
_app.use(function(request, result, next) {
result.setHeader('Access-Control-Allow-Origin', '*');
next();
});
this._app.listen(expressPort, () => {
console.info(`App listening on port ${expressPort} !`);
});
socket.ts
const socketPort = 3000;
const server = http.createServer(_app);
const io = socketIo(server);
server.listen(socketPort, undefined, undefined, () => {
console.info(`Sockets are listening on port ${socketPort} !`);
io.on('connection', (socket: Socket) => {
console.log("User connected");
});
});
nginx 配置
server {
listen 80;
listen [::]:80;
server_name _;
root /var/www/html;
index index.html;
location / {
try_files $uri $uri/ =404;
}
}
我尝试在我的 nginx conf 中添加它,但没有任何改变
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_cache_bypass $http_upgrade;
proxy_pass http://localhost:3000/;
}
【问题讨论】:
-
试试
proxy_pass http://localhost:3000;,不带斜杠。 -
@IvanShatsky 不工作,同样的问题
-
服务器上有防火墙吗?它可能会阻止连接。
标签: node.js angular express sockets nginx