2016-09-16 84 views
2

我有這些路由器express.js中聲明,我想知道爲什麼run user被觸發時,我打開本地主機:3000/myname /配置文件。路由器在express.js根據參數

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

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

我希望它不會,如何解決? 請任何人幫助我? 預先感謝您......

+0

我無法重現該問題。請發送其餘的代碼。 –

+0

真的發生了嗎? – Beginner

回答

0

您確定嗎?我試過你的代碼,它觸發了run user profile。可能你應該顯示所有的代碼。

1

只需重新排列代碼,如下所示,您的代碼應該可以正常工作。

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

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

的問題是,在該路線定義的順序,由於這兩種路線有/:username,當你打http://localhost:3000/myname/profile.,因爲它的URI匹配的第一個路由被優先考慮。

也可參考使用快遞路線命名和排序這個計算器後 - Node.js Express route naming and ordering: how is precedence determined?