【问题标题】:socket.io in production with node.js and reactsocket.io 在生产中使用 node.js 并做出反应
【发布时间】:2023-04-01 03:10:01
【问题描述】:

您好,我正在为生产设置我的第一个 socket.io 聊天应用程序。我正在使用 netlify 使用 React 和 Heroku 和 JAWSdb for mysql 来托管前端。这是我使用 Node.js 的后端代码

const port = process.env.PORT || 4000;
const router = require('./routes/routes');
const cors = require('cors');
const app = express();
const bodyParser = require('body-parser');
const session = require('express-session');
app.use('*', cors());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use(
  session({
    secret: 'cutiewithabooty',
    resave: true,
    saveUninitialized: true,
  })
);

const server = require('http').createServer(app);
const options = {
  cors: true,
  origins: ['http://127.0.0.1:4000'],
  'force new connection': true,
};
const io = require('socket.io')(server, options);

io.on('connection', (socket) => {
  const currentlyConnected = [];
  currentlyConnected.push(socket.id);
  console.log(currentlyConnected);
  console.log('connecting..', socket.id);

  socket.on('chat', (chat) => {
    console.log(chat);
  });

  socket.on('typing', (typing) => {
    io.sockets.emit('typing', typing);
  });

  socket.on('new_message', (data) => {
    io.sockets.emit('new_message', data);
  });

  socket.on('remove', (socket) => {
    console.log('user disconnected!');
  });
});

还有我的前端

import { io } from 'socket.io-client';
const ENDPOINT = 'http://localhost:4000';
var socket = io(ENDPOINT, { forceNew: true });

我不知道是否需要更改本地主机或如何调试,但这是我的控制台在浏览器中显示的内容。

【问题讨论】:

  • 试试:app.use(cors());
  • 另外,与问题无关的东西:app.use(bodyParser.urlencoded({ extended: true }));app.use(bodyParser.json()); 已弃用。相反,您可以使用:app.use(express.urlencoded({ extended: true }));app.use(express.json()); 参考:expressjs.com/en/api.html

标签: node.js reactjs express socket.io


【解决方案1】:

好的,我要做的就是将 Node.js 服务器更改为我的 netlify 应用程序

const server = require('http').createServer(app);
const options = {
  cors: true,
  origins: ['https://infallible-pasteur-b0e6fc.netlify.app'],
  'force new connection': true,
};
const io = require('socket.io')(server, options);

在我的客户端将端点更改为我的 heroku 应用程序

import { io } from 'socket.io-client';
const ENDPOINT = 'https://chatroom-express-db.herokuapp.com';
var socket = io(ENDPOINT, {
  forceNew: true,
  origins: 'https://chatroom-express-db.herokuapp.com',
});

还有沃利亚!有用。谢谢大家。

【讨论】:

    猜你喜欢
    • 2021-07-27
    • 1970-01-01
    • 2021-05-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-29
    • 2011-09-03
    • 1970-01-01
    相关资源
    最近更新 更多