所以基本上我想做的是構建一個帶有登錄系統的聊天應用程式,但由于某種原因我不能把它放在一起,當我加入房間時出現錯誤,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>
uj5u.com熱心網友回復:
那么問題是我使用了:
app.listen(5001, () => {
console.log("Server started on Port 5001");
})
代替:
server.listen(5001, () => {
console.log("Server started on Port 5001");
})
uj5u.com熱心網友回復:
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 });
});
})
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/371392.html
標籤:javascript 节点.js 插座 socket.io
