简体   繁体   中英

Node.js request.body undefined

This is my server.js file:

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

This is my index.js code in controllers folder:

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

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

This is my homeController.js code:

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

And this is my 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>
    })
})

When I make the post action req.body is undefined. How can I solve this problem?

Move app.use(bodyParser()); before route declaration controllers.init(app);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM