node.js - Passing route control with optional parameter after root in express? -


i'm working on simple url-shortening app , have following express routes:

app.get('/', function(req, res){   res.render('index', {     link: null   }); });  app.post('/', function(req, res){   function makerandom(){     var text = "";     var possible = "abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz0123456789";      for( var i=0; < 3 /*y u looking @ me <33??*/; i++ )       text += possible.charat(math.floor(math.random() * possible.length));     return text;   }   var url = req.body.user.url;   var key = makerandom();   client.set(key, url);   var link = 'http://50.22.248.74/l/' + key;   res.render('index', {     link: link   });   console.log(url);   console.log(key); });  app.get('/l/:key', function(req, res){   client.get(req.params.key, function(err, reply){     if(client.get(reply)){       res.redirect(reply);     }     else{       res.render('index', {         link: null       });     }   }); }); 

i remove /l/ route (to make url's shorter) , make :key parameter optional. correct way this:

app.get('/:key?', function(req, res, next){   client.get(req.params.key, function(err, reply){     if(client.get(reply)){       res.redirect(reply);     }     else{       next();     }   }); });  app.get('/', function(req, res){   res.render('index, {     link: null   }); }); 

not sure if need specify / route 1 "nexted" to. since other route updated post / route, imagine work fine.

that work depending on client.get when passed undefined first parameter.

something safer:

app.get('/:key?', function(req, res, next) {     var key = req.params.key;     if (!key) {         next();         return;     }     client.get(key, function(err, reply) {         if(client.get(reply)) {             res.redirect(reply);         }         else {             res.render('index', {                 link: null             });         }     }); }); 

there's no problem in calling next() inside callback.

according this, handlers invoked in order added, long next route app.get('/', ...) called if there no key.


Comments

Popular posts from this blog

c# - How to set Z index when using WPF DrawingContext? -

razor - Is this a bug in WebMatrix PageData? -

visual c++ - Using relative values in array sorting ( asm ) -