Passing route control with an additional parameter after root to express?

I am working on a simple URL shortening and have the 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; i < 3 /*yu looking at 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 would like to remove /l/ from my route (to reduce my url) and make the: key option optional. Would this be the right way to do 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 I need to indicate that my route / is the one that will be "next" to. But since my only other route would be my updated post / route, I would assume that it would work fine.

+46
express routes
Jul 22 '11 at 1:25
source share
1 answer

This will work depending on what client.get does when passing undefined as its first parameter.

Something like this would be 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 is no problem calling next () inside the callback.

According to this , handlers are called in the order in which they are added, since your next route is app.get ('/', ...) it will be called if there is no key.

+109
Jul 22 2018-11-11T00:
source share



All Articles