Answer the question
In order to leave comments, you need to log in
How to pass page '/' as page '/1' for pagination in node.js?
Good afternoon everyone, I wanted to start rendering pagination, but I ran into the following problem:
I'm pulling data from the database, displaying 10 records per page, but the whole problem is in the main page '/'. Pages '/' and '/1' should display the same data (last 10 records), but I can't set the offset to the main page (on page '/1' it is calculated) which is calculated by the formula limit * (page - 1 ), That is, when the user goes to the '/1' page, everything works, but he will initially go to the '/' page, and now nothing will be displayed on it, since the offset takes a negative value and an error is generated, how can I fix this problem? so that both '/' and '/1' are treated as '/1'
here is the code
router.get('/:page?', async (req, res, next) => {
let limit = 10;
let offset = 0;
try {
let { page = null } = req.params;
console.log(page);
console.log(req.params.page);
if (page !== null) {
page = Number(page);
if (Number.isNaN(page)) {
next();
return;
}
}
const result = await User.findAll({
limit: limit,
offset: offset,//limit * (page - 1),
order: [
['id', 'DESC']
]
})
res.render('index', { result });
//.catch(console.log.bind(console));
//console.log(result);
} catch (e) {
next(e);
}
});
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question