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

标签 javascript node.js express

我正在尝试掌握 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!"

有什么关于我做错的提示吗?

最佳答案

路由器路径是相对于挂载路径的。因此,您的联系人路由器将只是:

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

关于javascript - Express.js 4 路由与 router.route 不匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24111220/

相关文章:

javascript - Fabric.js - 动画时每 400 毫秒获取一次 oCoords 对象

javascript - 单击下一个弹出窗口时,第一个弹出窗口不会关闭

javascript - 脚本需要等待元素加载

javascript - 使用 Angular js 的 Controller 中的函数

json - Grunt 不会从 grunt-json-server 运行 json_server 任务

javascript - 如何使用函数、类和 req.pipe 模块化 Express 应用程序?

node.js - 如何将 create-react-app 作为大型网站的子目录提供服务?

javascript - Redux 订阅并撰写

json - 如何将 node.js sqlite3 记录集格式化为记录数组的 JSON 对象

javascript - 快速路由为每个请求的文件响应index.html