Ok so I've made a middleware that checks if the user has already submitted their data to a form, and if true; redirects them to an error page and a link to access their previous results if they wish to do that. Here is the middleware I've written:
module.exports.isRevisit = async (req, res, next) => {
const visitors = await Visitor.find({});
for (const visitor in visitors) {
if (visitor.session === visitors.session) {
const redirectedVisitor = visitors[visitor];
return res.render("error", { redirectedVisitor });
} else {
next();
}
}
};
and here is the route on which I've put my middleware:
app.post("/home", isRevisit, async (req, res, next) => {
const date = new Date();
const today = date.getDate();
const visitor = new Visitor({
input: req.body.input,
Date: today,
session: req.sessionID,
});
await visitor.save();
const goodVisitorsCount = await Visitor.count({ input: "good", Date: today });
const badVisitorsCount = await Visitor.count({ input: "bad", Date: today });
const allVisitorsCount = await Visitor.count({});
//console.log(visitor.session);
res.render(`GoodOrBad/${req.body.input}`, {
goodVisitorsCount,
badVisitorsCount,
allVisitorsCount,
});
});
Now when I hit the post route as a user who has yet to input their data for the first time. The page loads infinitely, but the middleware works and prevents any user from tampering with the form again. Any way to fix this? I'm super lost on this one. This is my first project using express, mongoose, and node.js!
CodePudding user response:
If visitors
is empty, the body of the for
loop is never executed, so your middleware calls neither res.render
nor next
. But one of them must be called.
Also, if the body of the for
loop is executed more than once, next
might be called during the first exeuction and res.render
during a subsequent execution. Or next
might be called more than once. All this does not make sense.
You must make sure that either next
is called once or res.render
is called once, no matter how often the loop is executed.
I cannot be more specific, because it is unclear to me how you know who the current visitor is. That information must come from the req
request object somehow.