【问题标题】:React + Socket.IO / Express on HerokuHeroku 上的 React + Socket.IO / Express
【发布时间】:2019-02-11 04:18:54
【问题描述】:

我正在使用 Heroku 来托管我的 React 应用程序,并带有 Express/Socket.IO 服务器。 在localhost 上一切正常,但是当我部署到 Heroku 时,它无法正常工作(控制台上没有错误)

客户

export default class Client extends Component {
    constructor() {
        super()
     /* on localhost: 
        this.socket = io('localhost:5001') */
        this.socket = io()
    }

    componentDidMount() {
        this.socket.on('...', () => {
            ...
        })
    }

    componentWillUnmount() {
        this.socket.disconnect()
    }

    render() {
        return (
            <div>
              Client
            </div>
        )
    }
}

服务器

const express = require('express');
const path = require('path');
const PORT = process.env.PORT || 5000;
const app = express();
const bodyParser = require('body-parser');
require('dotenv').config();

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

app.use(express.static(path.resolve(__dirname, '../react-ui/build')));

require('./socket.js')(app)

    // All remaining requests return the React app, so it can handle routing.
app.use('', function (req, response, next) {
  response.sendFile(path.resolve(__dirname, '../react-ui/build', 'index.html'));
});

app.listen(PORT, function () {
  console.error(`Listening on port ${PORT}`);
});

socket.js

module.exports = function (app) {
    const http = require('http')
    const socketIO = require('socket.io')
    const server = http.createServer(app)
    const io = socketIO(server)

    io.set('origins', '*:*');
    io.on('connection', function (client) {
       console.log('user connected')
    })

    /* on localhost:
       server.listen(5001, 'localhost') */
}

【问题讨论】:

    标签: node.js reactjs express heroku socket.io


    【解决方案1】:

    问题是socket io 需要在某个地方监听。你传递的app 参数没有监听任何东西,所以你应该做的是将 app.listen 附加到一个变量,然后将该变量传递给你的 socket.js 函数。然后你直接用 socketio(server) 连接。

    伪代码如下:

    服务器

    let server = app.listen(port)
    require('./sockets.js')(server)
    

    socket.js

    module.exports = function (server) {
    const socketIO = require('socket.io')
    const io = socketIO(server)
    io.set('origins', '*:*');
    io.on('connection', function (client) {
       console.log('user connected')
    })
    }
    

    【讨论】:

      猜你喜欢
      • 2017-01-18
      • 2014-06-27
      • 1970-01-01
      • 2020-06-28
      • 2014-06-10
      • 1970-01-01
      • 2012-07-25
      • 2017-06-05
      • 2018-06-19
      相关资源
      最近更新 更多