I am attempting to simplify some web server code (Node.js and Express) and I would like to use only one app.get statement for simplicity. I tried this:
app.get(url, function(req, res){
switch(url){
case "/":
res.sendfile('index.html');
res.writeHead(200, {"Content-Type": "text/plain"});
console.log("Client requested /");
break;
case "/profile":
res.sendfile('profile.html');
res.writeHead(200, {"Content-Type": "text/plain"});
console.log("Client requested /profile");
break;
default:
res.sendfile('404.html');
res.writeHead(404, {"Content-Type": "text/plain"});
console.log("Client requested page not found - 404 error");
}
});
But it's throwing a "reference error: url is not defined" error. Do I really need to code each potentially requested URL as a string literal for the first parameter and have multiple app.get statements or is there a way to use a switch case, or something comparable?
You can do a map based lookup to map a url and a resource. Package this in a middleware with app.use.
app.use(function(req, res){
routes = {
'/': 'index.html',
'/profile': 'profile.html'
};
var url = req.url;
if (routes[url] !== undefined) {
res.writeHead(200, {"Content-Type": "text/plain"});
res.sendfile(route[url]);
console.log("Client requested", url);
} else {
res.writeHead(404, {"Content-Type": "text/plain"});
res.sendfile('404.html');
console.log("Client requested page not found - 404 error");
}
});