处理POST提交

时间:2015-09-16 19:59:16

标签: node.js express

看起来像一个简单的任务,但我在代码中找不到错误。

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);
    });
};

当我发布表单时,我收到错误:

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)

在控制台中,我可以看到req.body未定义。为什么呢?

1 个答案:

答案 0 :(得分:1)

在进行路由之前,您需要进行配置,因此请在此行中向下移动:

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

在此之下:

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

......应该有用。