samedi 18 juin 2016

How to send a variable from node server to javascript client on page load?


My webapp is 99% static except for the fact that on page load, I want to send to the client their username if they are logged in and the name of the room they are connecting to if they specify that in the URL. These two variables need to be accessed in the client-side Javascript. So I've been trying to figure out what feels like a simple task but I am having little luck.

  1. Use templating engine.

    • Problem: Overkill because I only need it for one/two variables on an otherwise static page and I need to access it in the Javascript, not the HTML
  2. Make an AJAX request after page load

    • Problem: Causes flickering because first the page loads and then the DOM updates a second or two later because have to wait for the request to be sent and received. Also it's not efficient because it requires a second request/response.
  3. Use WebSockets

    • Problem: Same problem as above.
  4. Send it in the header information on page load

    • Problem: Can't access header information in Javascript unless you do a weird hack which only works as a separate AJAX call. Could just use #2 for that.

So what I ended up doing was using cookies and this works, 100%. There's actually no problems with it currently I just think the code is very ugly and fragile and I'm looking for a better way. Here's a snippet of what the cookie solution looks like:

app.get('/room/:roomName', function(req, res) {
    res.clearCookie('room');

    if (req.isAuthenticated()) {
        res.cookie('username', req.user.username);
    } else {
        res.cookie('username', '');
    }

    var roomName = req.params.roomName;

    if (roomNameToRoom.hasOwnProperty(roomName)) {
        res.cookie('room', req.params.roomName);
    }

    res.sendFile(path.join(__dirname, '../public/index.html'));
});

As you can see I grab the username from the request and validate the room and if it's valid, I send that back. I then parse the cookies with RegEx on the client side (very messy) and use those two variables in Javascript functions. I'm looking for alternative solutions that would allow me to send this all in one request while avoiding a lot of complexity and messiness.


Aucun commentaire:

Enregistrer un commentaire