由于连接 socket.io 时出现 xhr 轮询错误而获取 connect_error

Getting connect_error due to xhr poll error while connection of socket.io

我正在使用 socket.io 版本 4.1.3 我期待连接到服务器但收到错误 轮询-xhr.js:198 GET http://localhost:7000/socket.io/?EIO=4&transport=polling&t=Ni6qzFI 404(未找到)

服务器端:

import express from 'express';
import bodyParser from 'body-parser';
import cors from 'cors';
import mongoose from 'mongoose';
import { createServer } from 'http';
import { Server } from 'socket.io';
import postRoutes from './routes/routes.js';

const app = express();
app.use(bodyParser.json({ limit: '30 mb', extended: true }));
app.use(bodyParser.urlencoded({ limit: '30 mb', extended: true }));


app.use(cors());

//routes

app.use('/posts', postRoutes);
//database
const CONNECTION_URL = 'mongodb+srv://mernpratice:N9MapwYsjErP1wAm@cluster0.4skjb.mongodb.net/myFirstDatabase?retryWrites=true&w=majority';
const PORT = process.env.PORT || 7000;
const http = createServer(app);
const io = new Server(http, {
  cors:{
    origin:'*',
  }
});


io.on('connection', socket => {
  console.log('Conection to socket.io');
  socket.on('message', ({ name, message }) => {
    io.emit('message', { name, message })
  })
});

mongoose.connect(CONNECTION_URL, { useNewUrlParser: true, useUnifiedTopology: true })
  .then(() => app.listen(PORT, () => console.log(`Server Running on Port: http://localhost:${PORT}`)))
  .catch((error) => console.log(`${error} did not connect`));

mongoose.set('useFindAndModify', false);

和客户端

import io from 'socket.io-client';

const socket = io.connect('http://localhost:7000');

socket.on("connect_error", (err) => {
    console.log(`connect_error due to ${err.message}`);
  });

谢谢。

事实证明我正在为 mongoose 和 socket.io 使用 diff 服务器 当我设置创建的常量并将其用于两者时,问题就解决了。

import express from 'express';
import bodyParser from 'body-parser';
import cors from 'cors';
import mongoose from 'mongoose';
import { createServer } from 'http';
import { Server } from 'socket.io';
import postRoutes from './routes/routes.js';

const app = express();
app.use(bodyParser.json({ limit: '30 mb', extended: true }));
app.use(bodyParser.urlencoded({ limit: '30 mb', extended: true }));


app.use(cors());

//routes

app.use('/posts', postRoutes);
//database
const CONNECTION_URL = 'mongodb+srv://mernpratice:N9MapwYsjErP1wAm@cluster0.4skjb.mongodb.net/myFirstDatabase?retryWrites=true&w=majority';
const PORT = process.env.PORT || 7000;

const server = app.listen(PORT, () => {
  console.log("Listening on port: " + PORT);
});


mongoose.connect(CONNECTION_URL, { useNewUrlParser: true, useUnifiedTopology: true })
  .then(() => server )
  .catch((error) => console.log(`${error} did not connect`));

mongoose.set('useFindAndModify', false);


const io = new Server(server, {
  cors:{
    origin:'*',
  }
});


io.on('connection', socket => {
  console.log('Conection to socket.io');
  socket.on('message', ({ name, message }) => {
    io.emit('message', { name, message })
  })
});