Node.js Express: passing data from url and session to served JavaScript file

I am creating a websocket application where the client opens a link to the game instance and then the server tries to connect the client to the appropriate Socket.io room where the game will transmit information. For example, connecting to "/ game / abc" will load the game page and connect the socket on the page to room "abc" on the server.

The problem with this is that the JavaScript client file emits the game id and username of the connected user. I want it to act like this:

Client.js

var socket = io();
socket.emit("newUser", username, gameID); 

      

I was able to accomplish this by passing both client.html and client.js pages through the Express renderer Express:

Server.js

app.get(/^\/game\/([a-zA-Z0-9]*)$/, function(req, res){
    var game = req.params[0];
    var user = req.session.name; //gets username stored in session
    res.render("client.html", {username: user, gameName: game});
});

app.get(/game\/(.*)\/client.js/, function(req,res){
    res.render("client.js", {username: req.session.name, gameName: req.params[0]});
});

      

The second app.get () allows you to pass the name_name along with client.js through client.html as a parameter in the URL.

Client.html

 <script src="{{gameName}}/client.js"></script>

      

Finally, after two passes, the game id and username will be placed in client.js using the templating engine.

Client.js

var socket = io();
socket.emit("newUser", "{{username}}", "{{gameName}}");
//leads to socket.emit("newUser", "user", "abc"); when passed through renderer

      

While this gets the job done, it seems incredibly confusing and indirect. I was looking for alternatives to this, with an answer to node.js express rendering inside the included js files recommending using AJAX calls. However, I have not been able to figure out how to fine tune such an AJAX call. Is there a better way to overcome this problem?

+3


source to share


1 answer


You can simplify the whole thing and avoid displaying templates in Express to pass this variable in this case.

You already have a name available for your client code in the object window.location

. You can parse it manually with a simple regex (in this case) or you can use something called a client - side router , from which there are many possibilities.



There is one simple client-side router inspired by Express.js: Page.js , which will allow you to use very similar code that you are using right now in Express.

Many client frameworks have routers built in.

0


source







All Articles