I am in the process of creating a lobby where it should redirect the user to a game room with a url such as site.com/1234, where 1234 is the room code using Node.js and Socket.io. I have gotten to the step where when the user presses a button a request to the server is sent to connect to a room with a random room code. A message should then be sent back containing the url so that I may do window.location = url
. This should result in the correct link and send the user to a new HTML file.
The problem that I now have is that I have no clue on how to generate such a url or how to show the next html page after the request gets approved. I have seen some people say that I can do app.get("/:gameID")
but I lack the knowledge to implement it properly.
I have seen some other posts asking about this but the answers are either very vague or they are using some frame work. I would appreciate if someone could nudge me into the right direction.
CodePudding user response:
How I did it was by, like you said, setting up a route that allows you to have a parameter
app.get('/chat/:id', function(req,res){
res.sendFile('./public/chat/chat.html', { root: __dirname });
});
Then client side, trim the url and use socket.io to emit the room
let t = window.location.href.substring(window.location.href.lastIndexOf("/") 1)
// on connection, tries to login to the chat with the chat ID made
socket.on('connect', function(){
socket.emit('loginchat', {id: t});
});
Server side again:
socket.on('loginchat', async function(data){
socket.room = data.id;
//console.log(socket.room)
socket.join(data.id);
});
so when a user accesses the /chat route with a param, the server will access it, and send them to the appropriate room.
I wrote this a bit fast so apologies for any confusing bits, if you are stuck on part of it let me know :)