ceth
ceth

Reputation: 45285

Handling POST submission

Looks like a simple task, but I can not find out the error in my code.

app.js

var http = require('http');
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var routes = require('./routes')(app);

app.use(bodyParser.urlencoded({
    extended: true
}));
app.use(bodyParser.json());


app.set('view engine', 'jade');
app.set('views', './views');

app.use(express.static('./public'));

app.listen(3000, function() {
    console.log('hello');
    console.log('express server listening on port:' + 3000);
});

index.jade

html
    head
        title Welcome
    body 
        p Enter your name and email address to become a member.
        form(action='/signup', method='post')
            div
                label Name
                input(type='text', name='name')
            div
                label Email
                input(type='text', name='email')
            div
                input(type='submit')  

routes.js

module.exports = function(app) {

    app.get('/', function(req, res) {
        res.render('index');
    });

    app.post('/signup', function(req, res) {
        console.log(req);
        console.log(req.body);

        var name = req.body.name;
        var email = req.body.email;

        console.log('Name: ' + name);
        console.log('Email: ' + email);
        res.json(req.body);
    });
};

When I post the form I get the error:

TypeError: Cannot read property 'name' of undefined
    at /Users/demas/temporary/express/1/routes.js:11:22
    at Layer.handle [as handle_request] (/Users/demas/temporary/express/1/node_modules/express/lib/router/layer.js:95:5)
    at next (/Users/demas/temporary/express/1/node_modules/express/lib/router/route.js:131:13)
    at Route.dispatch (/Users/demas/temporary/express/1/node_modules/express/lib/router/route.js:112:3)
    at Layer.handle [as handle_request] (/Users/demas/temporary/express/1/node_modules/express/lib/router/layer.js:95:5)
    at /Users/demas/temporary/express/1/node_modules/express/lib/router/index.js:277:22
    at Function.process_params (/Users/demas/temporary/express/1/node_modules/express/lib/router/index.js:330:12)
    at next (/Users/demas/temporary/express/1/node_modules/express/lib/router/index.js:271:10)
    at expressInit (/Users/demas/temporary/express/1/node_modules/express/lib/middleware/init.js:33:5)
    at Layer.handle [as handle_request] (/Users/demas/temporary/express/1/node_modules/express/lib/router/layer.js:95:5)

In the console I can see the req.body is undefined. Why?

Upvotes: 0

Views: 295

Answers (1)

Drown
Drown

Reputation: 5982

You need to do your configuration before you do the routing, so moving down this line :

var routes = require('./routes')(app);

Below this :

app.use(bodyParser.urlencoded({
extended: true
}));
app.use(bodyParser.json());

... should work.

Upvotes: 1

Related Questions