一切似乎都运转良好,但是当试图达到' / posts / new'我得到" TypeError:无法读取属性' title' of null"引用' /routes/posts.js:24'这是在' /:title' GET方法。有什么想法吗?
'路线/ posts.js'
void DataGridView1_MouseWheel(object sender, MouseEventArgs e)
{
int currentIndex = this.DataGridView1.FirstDisplayedScrollingRowIndex;
int scrollLines = SystemInformation.MouseWheelScrollLines;
if (e.Delta > 0)
{
this.DataGridView1.FirstDisplayedScrollingRowIndex = Math.Max(0, currentIndex - scrollLines);
}
else if (e.Delta < 0)
{
if (this.DataGridView1.Rows.Count > (currentIndex + scrollLines))
this.DataGridView1.FirstDisplayedScrollingRowIndex = currentIndex + scrollLines;
}
}
&#39;视图/帖/新&#39;与Swig:
var express = require('express');
var router = express.Router();
var mongoose = require('mongoose');
var Post = mongoose.model('posts');
/* posts displays*/
// posts index
router.get('/', (req, res) => {
Post.find((err, posts) => {
res.render(
'posts/index',
{
title: 'Get All the Posts!',
posts: posts
}
);
});
});
// single post
router.get('/:title', (req, res) => {
var query = {"title": req.params.title};
Post.findOne(query, (err, post) => {
res.render(
'posts/post',
{
title: post.title,
date: post.date,
body: post.body
}
);
});
});
/* posts new */
router
// GET new posts route and form
.get('/new', (req, res) => {
res.render('posts/new', { title: 'Add a new Post' });
})
// POST new post data
.post('/new', (req, res) => {
new Post({
title: req.body.title,
date: req.body.date,
body: req.body.body
})
// Save post to db
.save((err, post) => {
res.redirect('/posts');
});
});
/* posts edit */
router
// GET the post
.get('/edit/:title', (req, res) => {
var query = {'title': req.params.title};
Post.findOne(query, (err, post) => {
res.render(
'posts/edit',
{
title: post.title,
date: post.date,
body: post.body
}
);
});
})
// PUT to update the post
.put('/edit/:title', (req, res) => {
var query = {'title': req.params.title};
var update = {
title: req.body.title,
body: req.body.body
};
var options = {new: true};
Post.findOneAndUpdate(query, update, options, (err, post) => {
res.render(
'posts/post',
{
title: post.title,
date: post.date,
body: post.body
}
);
});
})
// DELETE to delete a post
.delete('/edit/:title', (req, res) => {
var query = {'title': req.params.title};
Post.findOneAndRemove(query, (err, posts) => {
res.redirect('/');
})
});
module.exports = router;
答案 0 :(得分:2)
尝试将/new
的路由放在通用/:title
根目录之前。
因为首先定义了/:title
,所以如果它匹配则会首先调用它(它会这样做)。由于您没有名为“new”的帖子,因此您的数据库搜索会显示为空。你可能应该有一个错误处理程序。错误似乎在title: post.title
行。
如果首先定义/new
,如果匹配则会调用它。如果没有,则通用/:title
将更加通用。