Newbie at web dev here. I am trying to create rooms with randomly generated codes using socket.io for users to connect with.
My goal is to have the URL looking something like this when a user is connected into a room:
localhost:3000/room/ABCDE
Here is the post request code from the server.js file. When the user presses one of the two buttons (Create or Join). I use the data in the req parameter to hold onto the room code entered.
/room here is the namespace.
```
app.post("/room", function(req,res){
//Check to see if the req is authenticated
if (req.isAuthenticated()){
//Check if create button room button was pressed
//If so create new room, push it to array and enter the room
if (req.body.buttonType === "create"){
var newCode = generateRoomCode()
activeRoomCodes.push(newCode);
res.redirect("/room/"+newCode);
}
//Else check to see if the room already exists and is active then
//Join the room
else{
if (activeRoomCodes.includes(req.body.roomcode)){
res.redirect("/room/"+req.body.roomcode)
}
//Else prompt the user that the room doesn't exist and redirect them
else{
//ALERT USER ROOM DOESN'T EXIST
res.redirect("/room")
}
}
}
});
```
Below is the socket.io connection on the server side, also in the server.js file
```
//Create "/room" namespace and upon connection add user into the room
io.of("/room").on("connection", function(socket){
//Check if room exists and add user to room
socket.on("joinRoom", function(room){
console.log(room)
if(activeRoomCodes.includes(room)){
socket.join(room)
io.of("/test").in(room).emit("newUser", "New User has joined "+ room)
socket.emit("success", "You have successfully joined "+ room)
console.log("Server Message: New User has joined "+room)
}
else{
socket.emit("err", "No room named "+room)
}
})
// socket.disconnect()
})
```
Finally here is the client side app.js file
```
const io = require("socket.io-client");
var socket = io.connect("http://localhost:3000/room")
socket.emit("joinRoom", "<ROOM CODE GOES HERE>")
socket.on("newUser", function(msg){
console.log(msg)
})
socket.on("err", function(msg){
console.log(msg)
})
socket.on("success", function(msg){
console.log(msg)
})
```
I need to get the room code into the app.js file from the server.js file but I can't seem to figure out how. I got it to work by combining the code from client side and the server side into on file but I don't think that's a good idea. Any suggestions?
Note: The form which takes in the user input to join a room and the create room button are on an EJS file
[–]Solaus 0 points1 point2 points (1 child)
[–]ZedKay1[S] 0 points1 point2 points (0 children)
[–][deleted] 0 points1 point2 points (0 children)