Express.js 4个路由与router.route不匹配

我试图在Express 4中获得router.route的挂起权限。文档使得它听起来很棒,但是它不适合我。

如果我使用命令行工具制作标准应用程序,然后添加如下所示的routes / contacts.js:

var express = require('express'); var router = express.Router(); router.route('/:contactid') .get(function(req, res) { res.send('(get) It worked '+contactid); }) module.exports = router; 

然后在app.js中添加:

 var contacts = require('./routes/contacts'); ... app.use('/contacts', contacts); 

我期望http://localhost:8000/contacts/1匹配来自contacts.js的路由。 但是,我收到一个错误,基本上表明它不匹配contacts.js中的任何路由

 Error: Not Found at Layer.app.use.res.render.message [as handle] (project1/app.js:31:15) at trim_prefix (project1/node_modules/express/lib/router/index.js:226:17) at c (project1/node_modules/express/lib/router/index.js:198:9) at Function.proto.process_params (project1/node_modules/express/lib/router/index.js:251:12) at next (project1/node_modules/express/lib/router/index.js:189:19) at next (project1/node_modules/express/lib/router/index.js:150:14) at next (project1/node_modules/express/lib/router/index.js:166:38) at Function.proto.handle (project1/node_modules/express/lib/router/index.js:234:5) at Layer.router (project1/node_modules/express/lib/router/index.js:23:12) at trim_prefix (project1/node_modules/express/lib/router/index.js:226:17) 

如果我使用静态前缀添加路由,它按预期工作:

 router.get('/1', function(req, res) { res.send('It worked!'); }); // http://localhost:8000/contacts/1 says "It worked!" 

任何提示我做错了什么?

路由器path是相对于已安装的path。 所以你的联系人路由器将只是:

 router.route('/:contactid') .get(function(req, res) { res.send('(get) It worked ' + req.params.contactid); }) 

我认为这应该工作(对我来说)

在routes / contacts.js中

 /* Created by matthias on 6/9/14. */ var express = require('express'); var router = express.Router(); router.get('/:contactid', function(req, res) { res.send('(get) It worked ' + req.params.contactid); }); module.exports = router; 

然后在app.js

 var contacts = require('./routes/contacts'); var app = express(); app.use('/contacts', contacts); 

适用于我:localhost:3000 / contacts /:3

可以预料得到:(得到)它工作3