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

编程入门 行业动态 更新时间:2024-10-23 14:22:06
本文介绍了Express.js 4路由与router.route不匹配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在尝试在Express 4中解决router.route的问题,文档听起来很棒,但是对我来说不起作用.

I'm trying to get the hang of router.route in Express 4. The docs make it sound awesome, but it's just not working for me.

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

If I use the command line tool to make a standard app and then add routes/contacts.js that looks like this:

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中添加:

Then in app.js add:

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

我希望localhost:8000/contacts/1匹配来自contacts.js的路由.但是,我得到一个错误,该错误实质上表明它与contacts.js中的任何路由都不匹配

I'd expect localhost:8000/contacts/1 to match the route from contacts.js. However, I get an error that essentially indicates it's not matching any routes in 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)

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

If I add routes using a static prefix, it works as expected:

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

关于我在做什么错的任何提示吗?

Any tips on what I'm doing wrong?

推荐答案

路由器路径是相对于已安装路径的.因此,您的通讯录路由器将改为:

Router paths are relative to the mounted path. So your contacts router would instead just be:

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

更多推荐

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

本文发布于:2023-11-26 00:11:30,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1631895.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:路由   不匹配   js   Express   router

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!