我有Express和MongoDB的Node应用程序。它有3条路线:/文章,/方向和/研究。所有3条路线都在db中呈现来自不同集合的标题,当我点击标题时,它会导航到其余的数据,路径如下所示:http:// localhost:3000 / articles / 59df896b7f13f25b9009c42e。当我尝试通过链接从那条路线导航到/路线时它起作用,路径看起来像这样:http:// localhost:3000 /应该是方向。但是当我尝试导航(从这里http:// localhost:3000 / articles / 59df896b7f13f25b9009c42e)到/ research时,路径看起来像这样http:// localhost:3000 / articles / research并抛出错误。正确的路径应该是:http:// localhost:3000 / research。它只有在我尝试导航到/研究时才起作用。所有3条路线使用相同的逻辑和代码。我只是用方向替换文章等等。
所以,我的问题是为什么应用程序导航到错误的路径?
代码片段 - app / routes / directions.js,app / routes / articles.js和app / routes / websites.js(我得到TypeError:无法读取未定义的属性'author'//获取一篇文章,但是只有当导航到/研究时才会如前所述。如果我从/方向做同样的事情我会得到同样的错误,但如果我尝试从/研究导航到任何路线它工作正常):
// get one direction
router.get('/:id', (req, res) =>
Direction.findById(req.params.id, (err, direction) =>
User.findById(direction.author, (err, user) =>
res.render('direction', {direction, author: user.name}))))
// get one article
router.get('/:id', (req, res) =>
Article.findById(req.params.id, (err, article) =>
User.findById(article.author, (err, user) =>
res.render('article', {article, author: user.name}))))
// get one researcher
router.get('/:id', (req, res) =>
Researcher.findById(req.params.id, (err, researcher) =>
User.findById(researcher.author, (err, user) =>
res.render('researcher', {researcher, author: user.name}))))
已编辑。已添加其他代码片段。
来自app / app.js的代码片段
// article route
app.get('/news', (req, res) =>
Article.find({}, (err, articles) => {
if (err) {
console.log(err)
} else {
res.render('news', {title: 'articles', articles})
}
}))
// direction route
app.get('/direct', (req, res) =>
Direction.find({}, (err, directions) => {
if (err) {
console.log(err)
} else {
res.render('direct', {title: 'directions', directions})
}
}))
// researcher route
app.get('/research', (req, res) =>
Researcher.find({}, (err, researchers) => {
if (err) {
console.log(err)
} else {
res.render('research', {title: 'researchers', researchers})
}
}))
应用程序/视图/ research.pug
extends layout
block content
h1.page-header #{title}
ul.list-group
each researcher, i in researchers
li.list-group-item
a.newsLinks(href='/researchers/' + researcher._id)= researcher.title
应用程序/视图/ article.pug
extends layout
block content
h1.page-header= article.title
h5 Written by #{author}
p= article.body
hr
if user
if user.id ==article.author
a.btn.btn-default(href='/articles/edit/' + article._id)
span.glyphicon.glyphicon-edit
| Edit
a.btn.btn-danger.delete-article(href='#' data-id=article._id)
span.glyphicon.glyphicon-remove
| Delete
应用程序/视图/ layout.pug
li
a(href='/news')
| News
if user
li
a(href='/articles/add')
span.glyphicon.glyphicon-plus
| Add Article
li
a(href='/direct')
| Direction
if user
li
a(href='/directions/add')
span.glyphicon.glyphicon-plus
| Add Direction
li
a(href='research')
| Researchers
if user
li
a(href='/researchers/add')
span.glyphicon.glyphicon-plus
| Add Researcher
答案 0 :(得分:2)
您的href似乎有问题。
li
a(href='research')
| Researchers
应该是
li
a(href='/research')
| Researchers
相对于您的根文件夹。