2

I have these router declared in express.js, I wonder why the run user got triggered when I open localhost:3000/myname/profile.

router.get('/:username', function(req, res, next)
{
    console.log('run user')
});

router.get('/:username/profile', function(req, res, next)
{
    console.log('run user profile')
});

I expect it won't,how to solve that? please anyone help me? Thank you in advance....

Avdhesh
  • 15
  • 5
Maria Jane
  • 2,353
  • 6
  • 23
  • 39

2 Answers2

1

Just rearrange the code as shown below and your code should work fine.

router.get('/:username/profile', function(req, res, next)
{
   console.log('run user profile')
});

router.get('/:username', function(req, res, next)
{
    console.log('run user')
});

The issue is with the order in which the routes are defined, Since both the routes have /:username when you hit http://localhost:3000/myname/profile., the first route is given preference since it matches the uri.

Also refer this stackoverflow post on express route naming and ordering - Node.js Express route naming and ordering: how is precedence determined?

Community
  • 1
  • 1
Ananth Pai
  • 1,939
  • 14
  • 15
0

Are you sure about that? I tried your code and it triggered run user profile.May you should show the all code.

王如锵
  • 941
  • 7
  • 17