I have been looking around the web for a way to get the URL that is like:
example.com/games/game1 instead of example.com/games?id=game1
I have looked around the Node.JS website but I couldn't find anything that seemed to apply to my situation.
Any help is very appreciated. I have found an answer that did this using a .HTACCESS file, but I couldn't find a node.js alternative. The question/answer that I found was, creating nice looking URLs
Any help is very appreciated.
This URL example.com/games?id=game1 is passing the id as a GET parameter. To replace it with example.com/games/game1, you just have to come with a strategy on how to pass this id. This strategy is usually referred to node.js as routes, and, they are plenty of options on how to achieve your goal:
app.get('/games/:id', games.view);
Then, in your game.js file:
exports.view = function(req, res){
console.log(req.params.id); //gives you game1
//...
};
- Another way to do it is to use something specific for routing (instead of a whole framework). Director comes to mind.
var viewGame = function(gameId) { console.log(gameId); };
var routes = {
'/games/:gameId': viewGame
};
You can list to all requests, then parse request.url to decide which page to render or whether to return a 404 / 302 or whatever you want to do. This is just a small example. You probably want to separate your routing from your logic:
var http = require("http");
http.createServer(function(request, response) {
var parts = request.url.split('/');
if(parts[0] === 'games'){
var id = parts[1];
// Check if valid id
// And render the correct page
}
}).listen(80);