簡體   English   中英

如何在heroku上部署socket io和express服務器

[英]How to deploy socket io & express server on heroku

我正在嘗試在 heroku 上為聊天應用程序部署 socket io + express 服務器,但在部署服務器時遇到了問題。

首先這是我的服務器代碼

var express = require('express');
var app = express();
var server = require('http').createServer(app);
var io = require('socket.io').listen(server);
users = [];
connections = [];

server.listen(process.env.PORT || 3000);
console.log('Server running...');

io.sockets.on('connection',function(socket){
connections.push(socket);
console.log('Connected %s sockets connected ', connections.length);


//Disconnect 
socket.on('disconnect', function(data){
  users.splice(users.indexOf(socket.username),1);
  connections.splice(connections.indexOf(socket),1);
  console.log('Disconneted : %s sockets connected',connections.length);
  
});

});

這是我的 package.json 文件

  {
 "name": "",
 "version": "1.0.0",
 "description": "chat application",
 "main": "index.js",
 "scripts": {
 "start": "node index"
 },
 "author": "",
 "license": "ISC",
 "dependencies": {
 "socket.io": "*",
 "express": "*"
 }
 }

但我收到這個錯誤

不能獲取 /

此錯誤沒有錯誤部署的應用程序。 您的應用程序仍在等待端口 3000(或來自 process.env.PORT 的端口)上的連接。 應用程序響應“無法獲取 /”,因為您沒有任何路由。

要了解如何實現路由,請查看此 -> https://expressjs.com/en/starter/hello-world.html

要了解如何使用 socket.io(客戶端部分)進行連接,請查看此 -> https://socket.io/get-started/chat/#Integrating-Socket-IO

有同樣的問題(socket.io with express 和 react)。

您可以將此行添加到服務器:

app.use(express.static('some path to a static file'));

例如app.use(express.static('client/build'))

假設 package.json 在“腳本”中有這一行,對我有用:

"heroku-postbuild": "NPM_CONFIG_PRODUCTION=false npm install --prefix client && npm run build --prefix client"

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM