在Heroku上部署应用程序时,我在Socket io上遇到了问题

时间:2020-02-18 18:32:50

标签: node.js express socket.io

我在我的Express应用程序中使用socket.io创建了一个聊天室,它在本地主机上运行良好 当我将应用程序部署到heroku时,打开聊天室

时收到此错误
GET http://localhost:5000/socket.io/?EIO=3&transport=polling&t=N1PV-tt net::ERR_CONNECTION_REFUSED

这是我的index.js文件

var express = require("express")
var cors = require("cors")
var bodyParser = require("body-parser")
var app = express()
var mongoose = require("mongoose")
//var http = require('http').createServer(app);
var io = require('socket.io')(http)
var port = process.env.PORT || 5000
var server = app.listen(port);
var io = require('socket.io').listen(server);
var http = require('http');

let users = [];
let messages = [];
let index = 0;

app.use(bodyParser.json())
app.use(cors())
app.use(bodyParser.urlencoded({ extended: false }))

const mongoURI = 'mongodb+srv://1920:1920@cluster0-qyzs9.mongodb.net/liebherr?retryWrites=true&w=majority'

mongoose.connect(mongoURI, { useNewUrlParser: true })
    .then(() => console.log("MongoDB Connected"))
    .catch(err => console.log(err))

var Users = require("./routes/Users")

app.use("/users", Users)


//Socket connection

io.on('connection', (socket) => {
    io.emit('noOfConnections', Object.keys(io.sockets.connected).length)


    socket.on('disconnect', () => {
        console.log(`a user has left the chat.`);
        io.emit('noOfConnections', Object.keys(io.sockets.connected).length)
    })



    socket.on('chat-message', (msg) => {
        socket.broadcast.emit('chat-message', msg)
    })
    socket.on('typing', (data) => {
        socket.broadcast.emit('typing', data)
    })
    socket.on('stoptyping', () => {
        socket.broadcast.emit('stoptyping')
    })
})

    // Static folder
    app.use(express.static(__dirname + '/public/'));
    app.get(/.*/);


这是package.json文件

{
  "name": "express-demo",
  "version": "1.0.0",
  "description": "This is a full stack application",
  "engines": {
    "node": "13.1.0"
  },
  "main": "index.js",
  "scripts": {
    "start": "node index.js",
    "dev": "nodemon index.js"
  },
  "author": "Farouk Turki",
  "license": "ISC",
  "dependencies": {
    "bcrypt": "^3.0.7",
    "body-parser": "^1.19.0",
    "cors": "^2.8.5",
    "express": "^4.17.1",
    "jsonwebtoken": "^8.5.1",
    "mongodb": "^3.5.2",
    "mongoose": "^5.8.9",
    "nodemon": "^2.0.2",
    "socket.io": "^2.3.0"
  }
}

除了聊天室之外,其他所有东西都工作正常,所以我需要知道为什么它仍在本地主机中使用端口5000

1 个答案:

答案 0 :(得分:1)

从前端(socket.io客户端)将主机名设置为localhost。但是前端代码不是在服务器端运行的,而是在客户端(您的浏览器/或任何瘦客户端)中运行的,它只能访问可通过Internet访问的资源(或浏览器本身可以访问的资源) )。

因此,在您的情况下,连接代码将类似于:

<script>
  const socket = io('http://<your-heroku-public-url-for-the-express-server>');
  // which typically is 
  const socket = io('http://randomname.herokuapp.com');
</script>

假设http://randomname.herokuapp.com是您的节点js服务器的公共URL。