简体   繁体   中英

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

I've been building a web-socket application in which the client opens a link to a game instance, and then the server attempts to connect the client to the respective Socket.io room on which the game will transmit information. For example, connecting to '/game/abc' would load up the game page and connect the socket on the page to the 'abc' room on the server.

The problem with this is getting the client JavaScript file to emit the game ID and the username of the user connecting. I want it to act in the following way:

Client.js

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

I have managed to accomplish this by passing both my client.html and client.js page through an 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 for the gameName to be passed along to client.js through client.html in the form of a parameter in the url.

Client.html

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

Finally after two passes, the game ID and username both are put into client.js by the template engine.

Client.js

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

Although this gets the job done, it feels incredibly convoluted and indirect. I've looked up alternatives to this, with the answer at node.js express rendering inside included js files recommending to use AJAX calls. However, I have not been able to figure out how to exactly configure such an AJAX call. Is there a more effective way to overcome this problem?

You can simplify all of this and avoid rendering the templates in Express to pass that variable in this case.

You already have the gave name available to your client-side code in the window.location object. You can either parse it manually with a simple regex (in this case) or you can use something that is called a client-side router which there are a lot to choose from.

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

Many client-side frameworks have routers build in.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM