Mvrk Mvrk - 1 year ago 93
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'/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');
var db = mongoose.connection;
var app=express();

// set up routers

// set up view engine
app.set('view engine' , "ejs");

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

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

// 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'/register',function(req,resp){

var name=;
var username= req.body.username;
var email=;
var password= req.body.password;
var password2= req.body.password2;


my ejs file

<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>


Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download