带有 express 和 socket.io 的节点 js - 找不到 socket.io.js

Node js with express and socket.io -can't fint socket.io.js

所以基本上我想做的是构建一个带有登录系统的聊天应用程序,但由于某种原因我无法将它放在一起并且当我加入 chat.hbs 可以的房间时出现错误找不到 socket.io.js 文件,而且 main.js 正在使用 const socket = io(); 获取引用错误; (聊天应用程序在没有登录系统的情况下工作正常)

Failed to load resource: the server responded with a status of 404 (Not Found)
Uncaught ReferenceError: io is not definedat main.js:11

这是 app.js 文件

const express = require("express");
const path = require('path');


const http = require('http');
const socketio = require('socket.io');





const app = express();




const server = http.createServer(app);
const io = socketio(server);

const botName = "Bot";
app.use(express.static(path.join(__dirname, 'public')));

app.use(express.urlencoded({ extended: false }));
// Parse JSON bodies (as sent by API clients)
app.use(express.json());
app.use(cookieParser());

app.set('view engine', 'hbs');




  


//eldönti az útvonalat
app.use('/', require('./routes/pages'));
app.use('/auth', require('./routes/auth'));

app.listen(5001, () => {
  console.log("Server started on Port 5001");
})

这是main.js

const chatForm = document.getElementById('chat-form');
const chatMessages = document.querySelector('.chat-messages');
const roomName = document.getElementById('room-name');
const userList = document.getElementById('users');

// Felhasználó név és szoba név URL-ből
const { username, room } = Qs.parse(location.search, {
  ignoreQueryPrefix: true,
});

const socket = io();

// Csatlakozik chat szobába
socket.emit('joinRoom', { username, room });

// Lekérdezi a szobát felhasználókat
socket.on('roomUsers', ({ room, users }) => {
  outputRoomName(room);
  outputUsers(users);
});

和 chat.hbs

<script src="/socket.io/socket.io.js"></script>
<script src="/main.js"></script>

问题是我使用了:

app.listen(5001, () => {
console.log("Server started on Port 5001");
})

而不是:

server.listen(5001, () => {
console.log("Server started on Port 5001");
})

Szia,您需要等待 DOM 加载。

window.addEventListener('load', function () {   

  // Your code goes here
  const socket = io();

  socket.on("connect", () => {
    // you can only emit once the connection is established.
    socket.emit('joinRoom', { username, room });
  });

})