简体   繁体   English

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

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

So basically what i am trying to do is build a chat app with a login system but for some reason i cant put it together and i am getting an error when i join to the room the chat.hbs can't find the socket.io.js file and also the main.js is getting a reference error with the const socket = io();所以基本上我要做的是构建一个带有登录系统的聊天应用程序,但由于某种原因我无法将它放在一起,当我加入聊天室时出现错误。hbs 找不到 socket.io.js文件和 main.js 使用 const socket = io(); (the chat app works fine without the login system) (聊天应用程序在没有登录系统的情况下也能正常工作)

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

This is the app.js file这是 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");
})

This is the main.js这是 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);
});

And the chat.hbs还有chat.hbs

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

Well the problem was that I used:那么问题是我使用了:

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

instead of:代替:

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

Szia, you will need to wait for the DOM to load. 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 });
  });

})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM