node.jsexpressurl-routing

Handling url in express.js+node.js? accepting specific words, double slash and more


Homework:
I know few things about url handling in node.js

app.param('id', /^\d+$/);
app.get('/user/:id', function(req, res){
    res.send('user ' + req.params.id);
});

Will only accept /user/1, /user/2 ...i.e. with id as integer only

app.get('/:type(discussion|page)/:id', ...)  

will only accept type with value of discussion or page

app.param('range', /^(\d+)\-(\d+)?$/);
app.get('/range/range=:range', function(req, res){
var range = req.params.range;
    res.send('from ' + range[1] + ' to ' + range[2]);
});

will easily handle integer range and directly give us an array without any split or parsing and validation.

Question :

  1. Normally server accept www.example.com/path and www.example.com//path in same way but in node.js I have to write two separate app.get check to do that. How can I achieve this by only one check so that /path, //path, ///path gives same response

  2. I have one url which looks for /:path and path can take values listed in a dictionary

    var dict={ 
        "a":"You called a", 
        "b": "b is second", 
        "c": "cats are all over internet"
    }
    app.get('/:charc',function(req,res){ 
       res.send(dict[charc]);
    });
    

    How can I restrict app to accept only a,b,c without putting an if else condition. currently I am doing

    if (typeof dict[charc] == 'undefined') res.send(404, 'Sorry, we cannot find that!');
    
  3. Can I call range parameter(from homework part) sameway after '?' like

    app.get('/range?range=:range',...
    

    with url www.example.com/range?range=123-234


Solution

  • Regarding #1 if there's no better solution something like

    app.use(function (req,res,next) { 
        req.url = req.url.replace(/[\/]+/g, '/'); 
        next(); }
    ); 
    

    would make sure no subsequent routes would see any duplicate slashes. -@Andreas Hultgren

    Regarding #3, I'm pretty sure it's not possible to match query strings with express' router. Can't find a source that confirms this though. -@Andreas Hultgren