Friday, 12 May 2017

req.body.darkmode returns undefined from md-checkbox, but works with regular checkbox

I have this form: (PugJS)

form(method="post" action="/profile")
        md-list-item
            p: b Darkmode
            input(ng-change="changeTheme()" ng-model="darkmode" aria-
label="Darkmode switch" name="darkmode" type="checkbox")
        md-list-item
            p: b Admin
            input(ng-model="admin" aria-label="Admin switch" name="admin" 
type="checkbox")
        md-list-item
            md-button.md-raised.md-accent(type="submit") Save changes

and this in my router:

router.post('/profile', function(req, res, next){
    var User = mongoose.model("User");
    var user = new User();
    var darkmode = (req.body.darkmode) ? true : false;
    var admin = (req.body.admin) ? true : false;
    console.log(req.user.local.username);

    console.log(req.body.darkmode);
    console.log(req.body.admin);
    User.findOneAndUpdate({ "local.username": req.user.local.username }, {$set:{"local.darkmode": darkmode, "local.admin": admin}}, function(err, user) {
        if (err) throw err;
    });
    res.redirect('/profile');
});

However, the console.log returns undefined on req.body.darkmode. I have checked with the regular input(type="checkbox") and that works. They both have the name attribute.

I am using: AngularJs, Angular material, ExpressJS, nodeJS.

The package i am using to retrieve the body is the body-parser which I am retrieving on the top of my app.js



via Martijn Vissers

No comments:

Post a Comment