我正在为主页的博客帖子制作分页功能。
我为它创建了一个正在测试和工作的正则表达式,但是如果我重定向到'/'因为页码大于我的帖子数量,我收到Cannot GET '/'
错误..
更新:重定向时只有错误。正常访问时,它就像一个魅力
这是我的路由代码:
server.get(/^(\/)$|^(\/[0-9]*)$/g, co.wrap(function *(req, res, next) {
try {
console.log('hi');
const postRepo = repo_storage.get('post');
const skipper = req.originalUrl.substr(1);
const amount = 15;
const post_opts = {
skip: 0,
limit: 15
};
post_opts.skip = skipper !== '' ? (skipper - 1) * amount : 0;
const posts = yield postRepo.find({page: false, live: true}, post_opts);
// posts is an array of posts gotten from Mongo
if (posts.length === 0) {
console.log('redirecting...');
res.redirect('/');
return;
}
res.locals.body = {
posts
};
res.locals.page = 'home';
next();
return;
} catch (e) {
console.log('route / error', e);
res.sendStatus(500);
}
}));