我试图在Express 4中找到路由器路由器。文档让它听起来很棒,但它不适合我。
如果我使用命令行工具制作标准应用程序,然后添加如下所示的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!"
关于我做错了什么的提示?
答案 0 :(得分:3)
路由器路径相对于已安装的路径。所以你的联系人路由器只会是:
router.route('/:contactid')
.get(function(req, res) {
res.send('(get) It worked ' + req.params.contactid);
})
答案 1 :(得分:1)
我认为这应该有用(对我而言)
在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