4

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 ?

user12499410
  • 171
  • 8

4 Answers4

2

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.

0

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

Felipe Zavan
  • 1,043
  • 8
  • 21
0

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..
})
Quentin
  • 800,325
  • 104
  • 1,079
  • 1,205
Berk
  • 69
  • 7
-1

Solved:

app.use(express.urlencoded({
    extended: true
}));
user12499410
  • 171
  • 8
  • 1
    While this code may resolve the OP's issue, it is best to include an explanation as to how your code addresses the OP's issue. In this way, future visitors can learn from your post, and apply it to their own code. SO is not a coding service, but a resource for knowledge. Also, high quality, complete answers are more likely to be upvoted. These features, along with the requirement that all posts are self-contained, are some of the strengths of SO as a platform, that differentiates it from forums. You can edit to add additional info &/or to supplement your explanations with source documentation. – ysf Jun 21 '20 at 22:53