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

Time:12-01

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(); (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

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

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

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

CodePudding user response:

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");
})

CodePudding user response:

Szia, you will need to wait for the DOM to load.

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 });
  });

})
  • Related