Saturday, 15 April 2017

Rewrite URL parameter when using node.js and express without a redirect

I am using node.js, express, and sockets.io to:

  1. Find out whether or not the user has included a specific URL parameter when they arrive (working)
  2. If not, make a new random room ID and join the user to that room (working)
  3. Modify the address bar of the browser to reflect the new URL without redirecting the browser (unsure if possible, or how to accomplish)

First, I do not know if this is possible without violating DOM security. If it is, I would like to understand how I might be able to do it.

If it is not possible, and/or if I need to use a redirect, could you show me how to do it within my already working code within the working context of items #1 and #2?

var express = require('express');
var app = express();
var server = require('http').createServer(app);
var io = require('socket.io')(server);
var url = require('url');

app.use(express.static(__dirname + '/node_modules'));

app.get('/', function(req, res, next) {
  res.sendFile(__dirname + '/index.html');
  var roomID = req.query.me;
    if (roomID == null || !io.sockets.adapter.rooms[roomID]) {
      console.log("URL room variable is: " + roomID);
      console.log('New room!');
      roomID = Math.random().toString(36).substring(2, 13);
      joinRoom(roomID);
      console.log("+ you just joined new room: " + roomID);
    } else {
      joinRoom(roomID);
      console.log("URL room variable is: " + roomID);
      console.log("= you just joined existing room: " + roomID);
    }
});

function joinRoom(roomID) {
  io.on('connection', function(socket) {
    socket.join(roomID);
    io.sockets.in(roomID).emit('connectToRoom', "Joined room: http://localhost:3030/?me=" + roomID);
  });
  return;
}

server.listen(3030);

I do not have any sample code for the part that I'm trying to accomplish because I simply don't know where I should begin. So I would appreciate any direction (redirection? pun intended).

Thank you!



via Dshiz

No comments:

Post a Comment