Heroku部署NodeJS和ReactJS

时间:2019-04-20 00:00:29

标签: node.js reactjs heroku

我想在同一台Heroku机器上部署2个单独的项目。我在后面有前端和nodejs服务器的React应用程序。

它们通过本机中的localhost通过以下结构连接。在反应方面,使用以下客户端结构,可以看到Connected to : localhost:5000已打印。 :

import openSocket from 'socket.io-client';
socket = openSocket("http://localhost:5000");    
socket.on("connect", () => {
    console.log("Connected to : http://localhost:5000");
});

Node Side如下所示,并且在我的本地计算机上打印了Client connected

const server = require('http').createServer();
const io = require('socket.io')(server);
server.listen(5000, function(err) {
    if (err) throw err;
    console.log('Server Listening on port:', 5000);
});
io.on('connection', (client) => {
    console.log("Client connected!");
}

之后,我将项目部署在Heroku的2个不同的集群上。 NodeJS适用于https://<herokuname>.herokuapp.com/ 因此,我想知道是否要在React端编写openSocket方法,以便在该域上连接socketio连接。我尝试了以下方法,但没有一个起作用:

https://<herokuname>.herokuapp.com:5000/socket.io/?EIO=4&transport=websocket

https://<herokuname>.herokuapp.com/socket.io/?EIO=4&transport=websocket

ws://<herokuname>.herokuapp.com:5000/socket.io/?EIO=4&transport=websocket

ws://<herokuname>.herokuapp.com/socket.io/?EIO=4&transport=websocket

1 个答案:

答案 0 :(得分:1)

您必须将服务器绑定到Heroku为Web dynos提供的特定process.env.PORT

const server = require('http').createServer();
const io = require('socket.io')(server);
const PORT = process.env.PORT || 5000;
server.listen(PORT, function(err) {
    if (err) throw err;
    console.log('Server Listening on port:', PORT);
});
io.on('connection', (client) => {
    console.log("Client connected!");
}

一旦成功,您应该能够从客户端连接到根heroku服务器URL。

import openSocket from 'socket.io-client';
const url = "https://<herokuname>.herokuapp.com"
socket = openSocket(url);    
socket.on("connect", () => {
    console.log("Connected to:", url);
});

有关此主题的一些文档,请注意,如果您计划在heroku中使用socket.io,则可能希望打开会话关联:

https://devcenter.heroku.com/articles/dynos#local-environment-variables https://devcenter.heroku.com/articles/session-affinity