Mvrk Mvrk - 1 month ago 12
Node.js Question

Expressjs Body-Parser : how to solve "TypeError: Cannot read property 'name' of undefined" - already reviewed all previouse ansers

the code works fine till i want to get data from form , i use expressjs and already aware of body-parser but when i use router.post('/register',function()) i get this error :

The erro i get

TypeError: Cannot read property 'name' of undefined
at e:\2016\passport\controllers\users.js:20:23
at Layer.handle [as handle_request] (e:\2016\passport\node_modules\express\lib\router\layer.js:95:5)
at next (e:\2016\passport\node_modules\express\lib\router\route.js:131:13)
at Route.dispatch (e:\2016\passport\node_modules\express\lib\router\route.js:112:3)
at Layer.handle [as handle_request]


my app.js i already use body-parser

var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var exphbs = require('express-handlebars');
var expressValidator = require('express-validator');
var flash = require('connect-flash');
var session = require('express-session');
var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;
var mongo = require('mongodb');
var mongoose = require('mongoose');
var http=require('http');
mongoose.connect('mongodb://localhost/loginapp');
var db = mongoose.connection;
var app=express();

// set up routers
app.use(require('./controllers'));


// set up view engine
app.set('view engine' , "ejs");
app.set("views",path.join(__dirname,"views"));


// set up public files
app.use( express.static('public'));



// set up BodyParser Middleware
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(cookieParser());

// Express Port
http.createServer(app).listen(process.env.Port || 2000,function(){
console.log('login app Run!');
});


router file users.js ## i got the error message when i post this route

router.post('/register',function(req,resp){

var name= req.body.name;
var username= req.body.username;
var email= req.body.email;
var password= req.body.password;
var password2= req.body.password2;
resp.render('register');

});


my ejs file

<pre>
<form method="post" action="/users/register">
<input type="text" name="name">
<input type="text" name="username">
<input type="email" name="email">
<button type="submit" >Submit</button>
</form>

</pre>

Answer

You are requiring './controllers' before body-parser! body-parser should be called before any controllers in order to parse and attach the request body to req.

Comments