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. π
const express = require('express');
const router = express.Router();
const Employee = require('../models/employee');
router.get('/',(req, res) => {
res.render('index');
});
router.get('/employee/new', (req, res) => {
res.render('new');
});
router.post('/employee/new', (req, res) => {
let newEmployee = {
name : req.body.name,
designation : req.body.designation,
salary : req.body.salary
}
Employee.create(newEmployee).then(employee => {
res.redirect('/');
}).catch(err => {
console.log(err);
});
});
module.exports = router;
you can see clearly I have defined the newEmployee Object, so why ‘name’ is the property of undefined.
<div class="container mt-5 w-50">
<h2 class="mb-4">Add New Employee</h2>
<form action="/employee/new" method="POST">
<input type="text" name="name" class="form-control" placeholder="Employee Name">
<input type="text" name="designation" class="form-control" placeholder="Employee Designation">
<input type="text" name="salary" class="form-control" placeholder="Employee Salary">
<button type="submit" class="btn btn-danger btn-block mt-3">Add to Database</button>
</form>
</div>
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.
const bodyParser = require('body-parser');
app.use(bodyParser.json()); // for parsing application/json
app.use(bodyParser.urlencoded({ extended: true })); // for parsing application/x-www-form-urlencoded
Edit: Also, make sure that you use the body parser middleware before your router.
const employeeRoutes = require('./routes/employees');
app.use(bodyParser.json()); // for parsing application/json
app.use(bodyParser.urlencoded({ extended: true })); // for parsing application/x-www-form-urlencoded
// This needs to come AFTER the app.use calls for the body parser
app.use(employeeRoutes);