POST method return an empty object in Nodejs

Viewed 862

I have a simple form:

<form method="POST">
    <div class="form-group">
        <label>Email address</label>
        <input type="email" name="email" class="form-control" />
    </div>
    <div class="form-group">
        <label>Password</label>
        <input type="password" name="password" class="form-control" />
    </div>
    <button type="submit" class="btn btn-primary">Submit</button>
</form>

and I have a simple model:

const User = mongoose.model('User', {
    email: {
        type: String,
    },
    password: {
        type: String,
    }
});

and a simple post method

.post(async (req, res) => {
    console.log(req.body);
    const user = new User(req.body);
    try {
        const saveUser = await user.save();
        res.send(saveUser);
    } catch (error) {
        res.send(error);
    }
}

And yet, when i submit my form at the HTML file i get back an empty object.. i've tried every single one of SO solutions and none of them work for me.

NOTE: that i am using a JSON parser: app.use(express.json());.

please help ?

4 Answers

Your form is not sending JSON encoded data. Instead it uses application/x-www-form-urlencoded. Longer read Therefore you either need a bodyParser or you send the form data JSON encoded.

Try converting the user instance to a JSON string: res.send(saveUser.toJSON());

Make sure you have body-parser installed and imported to your project. npm i body-parser

 const bodyParser = require("body-parser")    
 app.use(bodyParser.urlencoded({ extended: true }));

This is the method I am familiar when it comes to create a new entry

let email = req.body.email
let password = req.body.password
let user = {email: email, password: password}

User.create(user, (err, newUser) => {
  if(err) // handle err
  else // do something - redirect, etc..
})

Solved:

app.use(express.urlencoded({
    extended: true
}));
Related