tbeauvais
tbeauvais

Reputation: 1738

Capture part of node.js route

app.get('/users/:userId/profile', ProfileHandler);
app.get('/page/:userId/profile', ProfileHandler);
app.get('/photo/:userId/profile', ProfileHandler);

If I have the above 3 routes, how can I capture the first part so that the handler knows what is being requested? I'd like to have users or page or photo sent to the handler as part of the request object.

Ideally I'd like to avoid making this a single route with a regex as this is just a dumbed down example of my real use case.

Upvotes: 1

Views: 115

Answers (2)

loganfsmyth
loganfsmyth

Reputation: 161647

If you know ahead of time due to your bindings, why not just pass the info in there?

app.get('/users/:userId/profile', ProfileHandler.bind(null, 'users'));

function ProfileHandler(pageRoot, req, res, next){
    switch (pageRoot){
        case 'users':

            break;
        case 'page':
            break;
    }
});

Upvotes: 1

Chris Tinsley
Chris Tinsley

Reputation: 161

Based on the pattern you are using , ProfileHandler will be passed a req and res object. req has a url property that you can then split and switch-case:

app.get('/users/:userId/profile', ProfileHandler);
app.get('/page/:userId/profile', ProfileHandler);
app.get('/photo/:userId/profile', ProfileHandler);

function ProfileHandler(req,res){
   var reqType = req.url.split('/')[1];
   switch(reqType){
       case 'users':
      //DO SOMETHING COOL 
       break;
    }
}

Alternatively, you could add middleware that set that value on the request.

app.use(function (req, res, next) {
    var reqType = req.url.split('/')[1];
    req.handlerTarget = reqType;
});

function ProfileHandler(req,res){
   switch(req.handlerTarget){
       case 'users':
      //DO SOMETHING COOL 
       break;
    }
}

Upvotes: 0

Related Questions