0
var express = require('express');

var exampleRouter = express.Router();

exampleRouter.get([
    '/example/cat/:id/subcat/:subId', /*1st URL*/
    '/example/:id/:subId/', /*2nd URL*/
    ],function(req, res){

if( *1st url condition*){ // It should enter here
  /*do something..*/
}else if( *2nd url condition* ){
  /*do something..*/
}

});

Suppose the request from browser is like this http://www.example.com/example/cat/1/subcat/2

What should be the 1st Url condition?

user3774128
  • 1
  • 1
  • 2

2 Answers2

0

You can use originalUrl or path:

console.log(req.originalUrl)

In your case (try it):

var express = require('express');    
var exampleRouter = express.Router();

projectRouter.get([
    '/example/cat/:id/subcat/:subId', /*1st URL*/
    '/example/:id/:subId/', /*2nd URL*/
    ],function(req, res){

    if(req.url == "/example/cat/:id/subcat/:subId"){ 
        // It should enter here do something..*/
    } else if(req.url == "/example/:id/:subId/"){
        // do something..
    }    
});

Or (more clean):

var express = require('express');    
var exampleRouter = express.Router();

projectRouter.get('/example/cat/:id/subcat/:subId',function(req, res){
    // It should enter here do something..    
});

projectRouter.get('/example/:id/:subId/',function(req, res){
    // Second route
});

The second way is more usual.

BrTkCa
  • 4,703
  • 3
  • 24
  • 45
  • originalUrl and path will give the exact request path not the path defined in router array. Suppose request from browser is like this http://www.example.com/example/cat/1/subcat/2 projectRouter.get([ '/example/cat/:id/subcat/:subId', '/example/:id/:subId/', ],function(req, res){ if( 1st url){ // It should enter here /*do something..*/ }else if( 2nd url ){ /*do something..*/ } }); – user3774128 Nov 11 '15 at 17:02
  • Agreed. But my requirement is to avoid repetition of common things in both route. So I thought of combining both route into one, also I need to do few difference. My doubt is if expressjs giving an option to route multiple paths from an array, why it can't give which one is selected? – user3774128 Nov 12 '15 at 05:16
0

something like this might work....

projectRouter.get([
    '/example/cat/:id/subcat/:subId', /*1st URL*/
    '/example/:id/:subId/', /*2nd URL*/
    ],function(req, res){

    var param = req.url.replace(/^\/|\/$/g, '').split('/');

    if(param[1] == "cat" && param[3] == "subcat"){ 

        // It should enter here do something..*/

    } else {

        // do something..

    }    
});
Shujaat
  • 691
  • 4
  • 18
  • This might work, but I was looking for an answer without regular expression. My doubt is if expressjs giving an option to route multiple paths from an array, why it can't give which one is selected? – user3774128 Nov 12 '15 at 05:11
  • The regular expression is to trim any beginning/trailing slashes. It can work without the regular expression too. – Shujaat Nov 12 '15 at 07:13