簡體   English   中英

NodeJS 和 ReactJS 的 Heroku 部署

[英]Heroku Deployment of NodeJS and ReactJS

我想在同一台 Heroku 機器上部署 2 個單獨的項目。 我有前端的 React 應用程序和后端的 nodejs 服務器。

它們通過我機器中的 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");
});

節點端如下所示, 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 個不同集群上。 https://<herokuname>.herokuapp.com/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

您必須將您的服務器綁定到 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!");
}

一旦它工作,你應該能夠從你的客戶端連接到 root 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

暫無
暫無

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

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