Node.js request.body undefined

时间:2014-05-07 09:24:29

标签: node.js

这是我的server.js文件:

var express = require("express");
var bodyParser = require("body-parser");
var controllers = require('./controllers');
var app = express();
controllers.init(app);

app.set('view engine', 'vash');

app.use(bodyParser());
app.use(express.static(__dirname + "/public"));
app.listen(5000);

这是我在controller文件夹中的index.js代码:

(function(controllers){
    var homeController = require('./homeController');

    controllers.init = function(app){
        homeController.init(app);
    };
})(module.exports);

这是我的homeController.js代码:

(function(homeController){
    homeController.init = function(app){
        app.get('/', function(req, res){
            res.render('index', {title: "The Board"});
        });

        app.post("/", function(req, res){
            console.log(req.headers);
            console.log(req.body);

        });
    };
})(module.exports);

这是我的HTML:

@html.extend('layout', function(model){
    @html.block('body', function(model){
        @if(model.error){
            <p class="text-error">Error occurred: @model.error</p>
        }

        <div class="row">
            <form action="/" method="post">Enter your name:
                <input type="text" name="userName" placeholder="..." />
                <br>
                <button type="submit">Submit</button>
            </form>
        </div>
    })
})

当我进行帖子操作时,req.body未定义。我该如何解决这个问题?

1 个答案:

答案 0 :(得分:1)

在路线声明app.use(bodyParser());

之前移动controllers.init(app);