How to Pass route control with optional parameter after root in express

0 votes

I'm working on a simple url-shortening app 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 /*y u 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 the /l/ from my route (to make my url's shorter) and make the :key parameter optional. Would this be the correct 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 specify that my / route is the one to be "nexted" to. But since my only other route would be my updated post / route, I would imagine it would work fine.

Oct 12, 2020 in Node-js by kartik
• 37,520 points
14,314 views

1 answer to this question.

0 votes

Hello @kartik,

That would work depending on what client.get does when passed 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's no problem in calling next() inside the callback.

Hope it helps!!

Thank you!!

answered Oct 12, 2020 by Niroj
• 82,840 points

Related Questions In Node-js

0 votes
1 answer

How to use the middleware to check the authorization before entering each route in express?

Hello @kartik, As long as app.use(authChecker); is before app.use(app.router); it will get ...READ MORE

answered Nov 30, 2020 in Node-js by Niroj
• 82,840 points
2,041 views
0 votes
1 answer

How to get GET (query string) variables in Express.js on Node.js?

Hello @kartik, Since you've mentioned Express.js in your ...READ MORE

answered Jul 8, 2020 in Node-js by Niroj
• 82,840 points
3,257 views
0 votes
1 answer

How to paginate with Mongoose in Node.js?

Hello @kartik, You can chain just like that: var ...READ MORE

answered Jul 15, 2020 in Node-js by Niroj
• 82,840 points
808 views
0 votes
1 answer

How to programmatically send a 404 response with Express/Node?

Hello @kartik, The method is: res.sendStatus(404); Express will send a ...READ MORE

answered Jul 16, 2020 in Node-js by Niroj
• 82,840 points
3,536 views
0 votes
1 answer

jQuery AJAX fires error callback on window unload - how do I filter out unload and only catch real errors?

Hello, In the error callback or $.ajax you have three ...READ MORE

answered Apr 27, 2020 in Java-Script by Niroj
• 82,840 points
4,190 views
0 votes
1 answer

How do I pass command line arguments to a Node.js program?

Hello @kartik, If your script is called myScript.js ...READ MORE

answered May 5, 2020 in Java-Script by Niroj
• 82,840 points
3,243 views
0 votes
1 answer

Error:Issue when trying to use IN() in wordpress database

Hello @kartik, Try this code : // Create an ...READ MORE

answered May 8, 2020 in PHP by Niroj
• 82,840 points
1,116 views
+2 votes
1 answer

How do I debug Node.js applications?

Hello @kartik, Use node-inspector  from any browser supporting WebSocket. Breakpoints, ...READ MORE

answered Jul 8, 2020 in Node-js by Niroj
• 82,840 points
1,028 views
0 votes
1 answer

How to include route handlers in multiple files in Express?

Hello @kartik, If you want to put the routes ...READ MORE

answered Jul 15, 2020 in Node-js by Niroj
• 82,840 points
5,802 views
0 votes
1 answer

How to setup route for websocket server in express?

Hello @kartik, You'll want to use the path option: var wss ...READ MORE

answered Oct 16, 2020 in Node-js by Niroj
• 82,840 points
5,467 views
webinar REGISTER FOR FREE WEBINAR X
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP