socket.io 无法连接到后端,出现 404 错误。

huangapple go评论68阅读模式
英文:

socket.io not connecting to backend with 404 error

问题

我正在尝试从我的前端(localhost:5173)连接到后端(localhost:5001)。然而,它一直给我404错误,无法连接。

以下是我的文件:

// 这个文件被导入到我的React app.js中
import { io } from 'socket.io-client';

export const socket = io.connect("http://localhost:5001/");

以及

require('dotenv').config();

const express = require('express');
const mongoose = require('mongoose');
const userRoutes = require('./routes/user');
const groupRoutes = require("./routes/group");
const forumRoutes = require("./routes/forum");
const cors = require('cors');
const app = express();

const http = require('http');
const { Server } = require("socket.io");
app.use(cors({
  origin: "http://localhost:5173"
}));
const server = http.createServer(app);
app.use(express.json());
const io = new Server(server, {
  cors: {
    origin: 'http://localhost:5173',
    methods: ['GET', 'POST'],
  }
});

io.on('connection', (socket) => {
  console.log(`User connected ${socket.id}`);
});

app.use((req, res, next) => {
  // console.log(req.path, req.method);
  next();
});

app.use('/api/user', userRoutes);
app.use('/api/group', groupRoutes);
app.use('/api/forum', forumRoutes);

mongoose.connect(process.env.MONGO_URI)
  .then(() => {
    app.listen(process.env.PORT, () => {
      console.log('listening on port', process.env.PORT);
    });
  })
  .catch((err) => {
    console.log(err);
  });

我是否有什么做错或粗心大意的地方?非常感谢!

英文:

I am trying to connect to my backend (localhost:5001) from my front end (localhost:5173). However, it keeps giving me error 404 cannot connect.

Here are my files below

// This file is imported into my react app.js
import { io } from 'socket.io-client';

export const socket = io.connect("http://localhost:5001/");

and

require('dotenv').config();

const express = require('express');
const mongoose = require('mongoose');
const userRoutes = require('./routes/user');
const groupRoutes = require("./routes/group");
const forumRoutes = require("./routes/forum");
const cors = require('cors');
const app = express();

const http = require('http');
const { Server } = require("socket.io");
app.use(cors({
  origin: "http://localhost:5173"
}));
const server = http.createServer(app);
app.use(express.json());
const io = new Server(server, {
  cors: {
    origin: 'http://localhost:5173',
    methods: ['GET', 'POST'],
  }
});



io.on('connection', (socket) => {
  console.log(`User connected ${socket.id}`);
});

app.use((req, res, next) => {
  // console.log(req.path, req.method);
  next();
});

app.use('/api/user', userRoutes);
app.use('/api/group', groupRoutes);
app.use('/api/forum', forumRoutes);

mongoose.connect(process.env.MONGO_URI)
  .then(() => {
    app.listen(process.env.PORT, () => {
      console.log('listening on port', process.env.PORT);
    });
  })
  .catch((err) => {
    console.log(err);
  });

Is there anything that I am doing wrong or careless? thank you so much!

答案1

得分: 1

套接字服务器绑定到由http.createServer(app)创建的HTTP server实例,而不是由app.listen()创建的HTTP服务器实例。

app.listen()方法做什么?请查看源代码:

app.listen = function listen() {
  var server = http.createServer(this);
  return server.listen.apply(server, arguments);
};

正如您所见,它创建了一个新的HTTP服务器实例。

应该是:

const app = express();
const server = http.createServer(app);
const io = new Server(server, {
  cors: {
    origin: 'http://localhost:5173',
    methods: ['GET', 'POST'],
  }
});
server.listen(process.env.PORT)

而不是:

const app = express();
const server = http.createServer(app);
const io = new Server(server, {
  cors: {
    origin: 'http://localhost:5173',
    methods: ['GET', 'POST'],
  }
});
app.listen(process.env.PORT)
英文:

The socket server is bound to the HTTP server instance created by http.createServer(app), not the HTTP server instance created by app.listen().

What does app.listen() method do? See the source code:

app.listen = function listen() {
  var server = http.createServer(this);
  return server.listen.apply(server, arguments);
};

As you can see, it creates a new HTTP server instance.

It should be:

const app = express();
const server = http.createServer(app);
const io = new Server(server, {
  cors: {
    origin: 'http://localhost:5173',
    methods: ['GET', 'POST'],
  }
});
server.listen(process.env.PORT)

NOT:

const app = express();
const server = http.createServer(app);
const io = new Server(server, {
  cors: {
    origin: 'http://localhost:5173',
    methods: ['GET', 'POST'],
  }
});
app.listen(process.env.PORT)

huangapple
  • 本文由 发表于 2023年6月16日 11:55:22
  • 转载请务必保留本文链接:https://go.coder-hub.com/76486873.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定