I'm using flash widely in my Node.js Express application, but for one route I can't get flash or redirect to work. Views are with pug:
form.permissive(action=`/setPermissive/${device._id}/${device.allowUnlock}` method="POST")
label.groupTitle(for="setPermissive") Allow Unlock
button.switch(type="submit" name="setPermissive")
label.switch
if (device.allowUnlock)
input(type="checkbox" name="setPermissive" checked)
else
input(type="checkbox" name="setPermissive" )
span.slider
route:
router.post('/setPermissive/:id/:permissive', catchErrors(deviceController.changePermissive));
controller:
exports.changePermissive = async (req, res) => {
const permissive = (req.params.permissive === "false") ? false : true;
const device = await Device.findOneAndUpdate({ _id: req.params.id }, { $set: { allowUnlock : !permissive } }, {
new: true
}).exec();
req.flash('success', `Successfully updated ${device.name}`);
res.redirect('/devices');
};
I know Device.findOneAndUpdate
executes because I can see it in the backend, but I do not get the flash message, I do not get redirected, and the UI does not reflect the update. If I manually refresh the page, I get the flash message and the UI is updated.
I have similar routes that flash and redirect as expected, e.g.:
form.form(action=`/changeStatusEnabled/${device._id}/${newStateEnabled}` method="POST")
input.button(type="submit" value=`${currentStateEnabled}` onclick=`return confirm('${msgConfEnabled}');`)
router.post('/changeStatusEnabled/:id/:state', catchErrors(deviceController.changeStatusEnabled));
exports.changeStatusEnabled = async (req, res) => {
const myBoo = (req.params.state === "enable") ? true : false;
const device = await Device.findOneAndUpdate({ _id: req.params.id }, { $set: { isEnabled: myBoo }}, {
new: true
}).exec();
req.flash('success', `Successfully updated ${device.name}`);
res.redirect(`/devicesAdmin`);
};
What am I missing?
For some reason the .permissive
class causes the hiccup. If anyone might know why, I'm all ears.
changed:
form.permissive(action=`/setPermissive/${device._id}/${device.allowUnlock}` method="POST")
label.groupTitle(for="setPermissive") Allow Unlock
button.switch(type="submit" name="setPermissive")
label.switch
if (device.allowUnlock)
input(type="checkbox" name="setPermissive" checked)
else
input(type="checkbox" name="setPermissive" )
span.slider
to:
form(action=`/setPermissive/${device._id}/${device.allowUnlock}` method="POST")
label.groupTitle(for="setPermissive") Allow Unlock
button.switch(type="submit" name="setPermissive")
label.switch
if (device.allowUnlock)
input(type="checkbox" name="setPermissive" checked)
else
input(type="checkbox" name="setPermissive" )
span.slider