【发布时间】:2020-08-24 00:10:38
【问题描述】:
我正在使用Express、EJS 和 MongoDB 开发 blogging application(单击链接以查看 GitHub 存储库)。
尝试对帖子进行分页时,我遇到了将 newerPosts 和 olderPosts 传递给视图的问题。我像 posts 变量(和其他变量)一样传递它们:
exports.getPosts = async (req, res, next) => {
//pagination params
var perPage = 10;
var currPage = req.body.page ? parseInt(req.body.page) : 1;
const newerPosts = function() {
currPage = currPage + 1;
console.log(currPage);
}
const olderPosts = function() {
currPage = currPage - 1;
console.log(currPage);
}
const posts = await Post.find({}, (err, posts) => {
if (err) {
console.log('Error: ', err);
} else {
res.render('default/index', {
moment: moment,
layout: 'default/layout',
website_name: 'MEAN Blog',
page_heading: 'XPress News',
page_subheading: 'A MEAN Stack Blogging Application',
posts: posts,
newerPosts: newerPosts,
olderPosts: olderPosts
});
}
})
.sort({
created_at: -1
})
.skip((currPage - 1) * perPage)
.limit(perPage)
.populate('category');
};
在视图中:
<div class="px-1">
<a class="btn btn-primary" href="#" onclick=<%="olderPosts()"%>>← Older Posts</a>
</div>
<div class="px-1">
<a class="btn btn-primary" href="#" onclick=<%="newerPosts()"%>>Newer Posts →</a>
</div>
然而,我从浏览器收到了Uncaught ReferenceError: newerPosts is not defined 错误消息。
我做错了什么? 最接近的可行替代方案是什么?
【问题讨论】:
标签: javascript node.js express ejs