I am working with Nodejs(Express.js), I am sending form data to "controller" but I am getting folllowing error
TypeError: Cannot read property 'name' of undefined
Here is my controller code,My req.body.name is not working
userController.save = function (req, res, next) {
var name = req.body.name;
console.log(name);
}
Here is my app.js, I am using MVC structure in nodejs
const express = require('express');
const mysql = require('mysql');
const expressValidator = require('express-validator');
const bodyParser = require('body-parser');
const cookieParser = require('cookie-parser');
const session = require('express-session');
const flash = require('connect-flash');
const app = express();
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use('/', routes);
app.set('view engine', 'pug');
app.set('views', path.join(__dirname, 'views'));
app.use(express.static(__dirname '/public'));
app.use(cookieParser('keyboard cat'));
const PORT = 4000
app.listen(PORT, function (err) {
if (err) console.log(err);
console.log("App started on PORT", PORT);
});
Here is my view file code(signup.pug)
form#myForm.my_form.pt-3(action='', method='POST')
.form-group
.row
.col-md-3
label(for='Name') Name
.col-md-9
input#name.form-control(type='text', name='name', placeholder='Enter your name')
.form-group
.row.pt-2
.col-md-12
input#submit.btn.btn-dark.form-control(type='submit', name='submit', value='Register')
CodePudding user response:
Although lacking of information, I believe your app.use('/', routes) must be put after the view engine, file path etc.
const express = require('express');
const mysql = require('mysql');
const expressValidator = require('express-validator');
const bodyParser = require('body-parser');
const cookieParser = require('cookie-parser');
const session = require('express-session');
const flash = require('connect-flash');
const app = express();
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.set('view engine', 'pug');
app.set('views', path.join(__dirname, 'views'));
app.use(express.static(__dirname '/public'));
app.use(cookieParser('keyboard cat'));
app.use('/', routes);
const PORT = 4000
app.listen(PORT, function (err) {
if (err) console.log(err);
console.log("App started on PORT", PORT);
});
CodePudding user response:
You are trying to access the name property on an undefined value, you can avoid this error by using req.body?.name
.