【问题标题】:Cannot connect socket.io with backend using react无法使用反应将socket.io与后端连接
【发布时间】:2023-03-19 17:54:01
【问题描述】:

我是新手,开始学习socket.io。我用express-generator 创建了我的后端,我安装了所有必需的依赖项,服务器工作正常,没有错误,但是,当我尝试从React 的前端连接socket.io 时,它给出了很多错误,我无法连接连接,我已经看到了所有的问题和答案,但无法修复它,所有代码都在下面给出。

信息:我已经从 bin/www 文件中导出服​​务器,并在后端将其导入 app.js 并且所有模块版本都是最新的

var server = http.createServer(app);
exports.server = server;

“快递服务器”

var createError = require("http-errors");
var express = require("express");
var path = require("path");
var cookieParser = require("cookie-parser");
var logger = require("morgan");
var cors = require("cors");
const { server } = require("./bin/www");
var io = require("socket.io")(server);

var indexRouter = require("./routes/index");
var usersRouter = require("./routes/users");

var app = express();

// view engine setup
app.set("views", path.join(__dirname, "views"));
app.set("view engine", "jade");
        
app.use(cors());
app.use(logger("dev"));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, "public")));

// Socket.io config

io.on("connection", (socket) => {
  console.log("Connected");
});

app.use("/", indexRouter);
app.use("/users", usersRouter);

// catch 404 and forward to error handler
app.use(function (req, res, next) {
  next(createError(404));
});

// error handler
app.use(function (err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get("env") === "development" ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render("error");
});

module.exports = app;

“反应”

import React from "react";
import socket from "socket.io-client";
import "./App.css";
        
const ENDPOINT = "http://localhost:3000";

function App() {
  const io = socket(ENDPOINT);
  return (
    <div className="App">
      <h1>Working</h1>
    </div>
  );
}

export default App;

登录后台

GET /socket.io/?EIO=4&transport=polling&t=NRtAs89 404 14.138 ms - 1362
GET /socket.io/?EIO=4&transport=polling&t=NRtAsNq 404 8.662 ms - 1362
GET /socket.io/?EIO=4&transport=polling&t=NRtAtc3 404 10.450 ms - 1362
GET /socket.io/?EIO=4&transport=polling&t=NRtAtrY 404 15.608 ms - 1362
GET /socket.io/?EIO=4&transport=polling&t=NRtAv3j 404 13.641 ms - 1362
GET /socket.io/?EIO=4&transport=polling&t=NRtAvJH 404 10.490 ms - 1362

Logs in console frontend

【问题讨论】:

  • sockets 问题标签通常与socket.io 标签不兼容 - 这是两个不同的东西。 sockets 指的是较低级别的套接字,例如原始 TCP / UDP 套接字。 socket.io 是高级库的名称。

标签: node.js reactjs express socket.io


【解决方案1】:

服务器未侦听任何传入连接。据我从您的代码中可以看出,您没有启动服务器。这就是为什么前端给你一个404 not found 的原因。你必须打电话给.listen()

为简单起见,我将所有内容都放在一个文件中。您可以稍后将它们分开用于您的文件/bin/www/

const express = require('express');

// Initialize the app
const app = express();

// Initialize socket.io server
const server = require('http').createServer(app);
const io = require('socket.io')(server);

PORT = 3003

// Start the Server (socket.io + express)
server.listen(PORT, () => {
    console.log(`Server is listening on port ${PORT}`);
});

更新:

如果你想绑定socket.ioexpress,你必须在调用.listen()之前绑定它,否则socket.io将无法启动。

我自己刚刚用express-generator 进行了测试。您需要将socket.io 逻辑移动到/bin/www。像下面这样:

const server = require('http').createServer(app);
const io = require('socket.io')(server);

旁注:

就个人而言,如果您要将socket.iosocket.io 结合使用,我建议您不要使用express-generatorexpress-generator 为您提供了一个严格的样板文件,其中无疑包含许多与您的应用程序无关的内容。加上模板仍然使用var 来分配变量。 ES6 已经问世 6 年了。

【讨论】:

  • 服务器正在运行,你写的代码已经在那里了,我做了一个路由并反复检查一切正常,只是socket.io没有
  • 但是你在哪里打电话给.listen()
  • 当您使用 express-generator 创建 express 应用程序时,它会在 bin/www 文件中侦听服务器,问题仅出现在 socket.io 上,否则一切正常
  • 我删除了 bin 文件夹并将必要的东西移到了 app.js 中,它现在可以工作了,非常感谢
  • @AvivLo 嗨,希望你很好,你能帮我看看这个问题吗? stackoverflow.com/questions/65682609/… 将不胜感激。
猜你喜欢
  • 2018-03-14
  • 2019-10-06
  • 2022-12-29
  • 1970-01-01
  • 2021-04-29
  • 1970-01-01
  • 1970-01-01
  • 2018-05-12
  • 1970-01-01
相关资源
最近更新 更多