Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.6k views
in Technique[技术] by (71.8m points)

node.js - Cannot connect socket.io with backend using react

I am newbie and starting learning socket.io. I created my backend with express-generator, I installed all required dependencies and the server working fine with no error, however, when I try to connect socket.io from frontend in React it gives many errors and I am not able to connect to connect, I have seen all the question and answer but cannot fix it, all code is given below.

info: I have exported server from bin/www file, and import it in app.js in backend and all modules version are latest

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

"Express 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;

"React"

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;

Logs in backend

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The server is not listening for any incoming connection. You didn't start the server as far as I can tell from your code. That's why the frontend is giving you a 404 not found. You have to call .listen()

I am putting everything in one file for simplicity's sake. You can separate them later one for your file in /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}`);
});

Update:

If you want to bind socket.io with express, you will have to bind it before you call .listen() Otherwise, socket.io won't start.

Just tested with express-generator myself. You will need to move the socket.io logic into /bin/www. Like the following:

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

Side Note:

Personally, I suggest you not to use express-generator if you are going to combine it with socket.io. express-generator gives you a rigid boilerplate that undoubtedly includes lots of things that are irrelevant to your app. Plus the template is still using var to assign variables. ES6 has been out there for 6 years already.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...