I am building a node Js project and i am saving the values of form to a mongoDB database.
Despite of trying i couldn’t find what is causing this error.
Error is at router.post
function on 3rd line.
Please guide me through this through your magical powers of coding and debugging. 😀
JavaScript
x
28
28
1
const express = require('express');
2
const router = express.Router();
3
const Employee = require('../models/employee');
4
5
router.get('/',(req, res) => {
6
res.render('index');
7
});
8
9
router.get('/employee/new', (req, res) => {
10
res.render('new');
11
});
12
13
14
router.post('/employee/new', (req, res) => {
15
let newEmployee = {
16
name : req.body.name,
17
designation : req.body.designation,
18
salary : req.body.salary
19
}
20
Employee.create(newEmployee).then(employee => {
21
res.redirect('/');
22
}).catch(err => {
23
console.log(err);
24
});
25
});
26
27
module.exports = router;
28
you can see clearly I have defined the newEmployee
Object, so why ‘name’ is the property of undefined.
JavaScript
1
10
10
1
<div class="container mt-5 w-50">
2
<h2 class="mb-4">Add New Employee</h2>
3
<form action="/employee/new" method="POST">
4
<input type="text" name="name" class="form-control" placeholder="Employee Name">
5
<input type="text" name="designation" class="form-control" placeholder="Employee Designation">
6
<input type="text" name="salary" class="form-control" placeholder="Employee Salary">
7
<button type="submit" class="btn btn-danger btn-block mt-3">Add to Database</button>
8
</form>
9
</div>
10
Advertisement
Answer
It doesn’t look like you’re using a body parser. Without one, req.body
will always be undefined, which looks like your issue. Try putting this before you define any of your routes.
JavaScript
1
4
1
const bodyParser = require('body-parser');
2
app.use(bodyParser.json()); // for parsing application/json
3
app.use(bodyParser.urlencoded({ extended: true })); // for parsing application/x-www-form-urlencoded
4
Edit: Also, make sure that you use the body parser middleware before your router.
JavaScript
1
8
1
const employeeRoutes = require('./routes/employees');
2
3
app.use(bodyParser.json()); // for parsing application/json
4
app.use(bodyParser.urlencoded({ extended: true })); // for parsing application/x-www-form-urlencoded
5
6
// This needs to come AFTER the app.use calls for the body parser
7
app.use(employeeRoutes);
8