【问题标题】:How to deploy socket io & express server on heroku如何在heroku上部署socket io和express服务器
【发布时间】:2019-07-07 17:36:14
【问题描述】:

我正在尝试在 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": "*"
 }
 }

但是我收到了这个错误

无法获取 /

【问题讨论】:

    标签: node.js heroku socket.io


    【解决方案1】:

    遇到了同样的问题(socket.io 带有 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"
    

    【讨论】:

      【解决方案2】:

      这个错误没有错误部署的应用程序。您的应用仍在等待端口 3000(或来自 process.env.PORT 的端口)上的连接。应用响应“Cannot GET /”,因为您没有任何路由。

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

      要了解如何使用 socket.io(客户端部分)进行连接,请查看 -> https://socket.io/get-started/chat/#Integrating-Socket-IO

      【讨论】:

        猜你喜欢
        • 2021-12-11
        • 1970-01-01
        • 2021-06-22
        • 1970-01-01
        • 2022-01-09
        • 1970-01-01
        • 2019-04-10
        • 2019-11-10
        • 1970-01-01
        相关资源
        最近更新 更多