Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 the form , I use expressjs and already aware of body-parser but when I use router.post('/register',function()) I get this error :

The error 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>
like image 676
Mvrk Avatar asked Dec 15 '22 03:12

Mvrk


2 Answers

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.

like image 72
Praveen Avatar answered Dec 21 '22 09:12

Praveen


Try setting up the routers as last, or definitely make sure your bodyParser is executed BEFORE it.

like image 35
Kevin Avatar answered Dec 21 '22 10:12

Kevin