ajax - Node.js Express: Passing data from URL and session into served JavaScript file -


i've been building web-socket application in client opens link game instance, , server attempts connect client respective socket.io room on game transmit information. example, connecting '/game/abc' load game page , connect socket on page 'abc' room on server.

the problem getting client javascript file emit game id , username of user connecting. want act in following way:

client.js

var socket = io(); socket.emit("newuser", username, gameid);  

i have managed accomplish passing both client.html , client.js page through express template renderer:

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 gamename passed along client.js through client.html in form of parameter in url.

client.html

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

finally after 2 passes, game id , username both put client.js template engine.

client.js

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

although gets job done, feels incredibly convoluted , indirect. i've looked alternatives this, answer @ node.js express rendering inside included js files recommending use ajax calls. however, have not been able figure out how configure such ajax call. there more effective way overcome problem?

you can simplify of , avoid rendering templates in express pass variable in case.

you have gave name available client-side code in window.location object. can either parse manually simple regex (in case) or can use called a client-side router there lot choose from.

there 1 simple client-side router inspired express.js: page.js, allow use similar code use right in express.

many client-side frameworks have routers build in.


Comments

Popular posts from this blog

c# - Validate object ID from GET to POST -

node.js - Custom Model Validator SailsJS -

php - Find a regex to take part of Email -