I want get username when user post it, but io.sockets.emit is not working. However, When i didn’t put io.sockets.emit on app.post, It is working.
my html
<html>
<body>
<form action="chat" id="main" method="post">
<div>
<input type="text" id="id" name="username" value="" placeholder=" " required />
<label for="id">暱稱</label>
</div>
<div>
<input type="text" id="key" name="key" value="" placeholder=" " />
<label for="key">房號</label>
</div>
<button type="submit" value="加入房間" class="btn">加入房間</button>
</form>
</body>
</html>
my js
io.on('connection', (socket) => {
socket.on('joinRoom', username => {
console.log(username);
console.log("joinRoom");
});
socket.on('chat message', msg => {
const user = getCurrentUser(socket.id);
console.log(user);
io.emit('chat message', msg);
});
});
app.post('/chat', urlencodedParser, function (req, res) {
io.sockets.emit('joinRoom', "aa")
console.log(req.body)
res.sendFile('public/chat.html', { root: __dirname })
});
‘joinRoom’ seems not receive anything.