I am using a middleware body-parser
to encoded the form values to get in req.body object.
But as I debug my code, found out req.body is undefined. Here is my code
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({ extended: false }));
Listen Post request
app.post('/newCategory', function (req,res) {
//express attached the form encoded values into body
var categoryName = req.body.categoryName;
});
Html Form
<form action="/newCategory" role="form" method="post" class="form-inline">
<input type="text" name="categoryName" placeholder="Category name" class="form-control" />
<input type="submit" value="New Category" class="btn btn-primary" />
</form>
I noticed that the order is very important. Usually the router should be declared in the end before starting the server . Eg: 1.i import the required files
var express = require("express");
var bodyParser = require("body-parser");
var morgan = require("morgan");
var db = require("./db.js");
var app = express();
2.i declare the other stuffs
app.set("port", process.env.PORT || 3000);
//app.use(express.static(__dirname + '/public'));
app.use(morgan('dev') ); // Log every request to console
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(bodyParser.json());
3. AFTER I INCLUDE ROUTES - most important step
var routes = require('./routes/routes');
routes(app); //routes shall use Express
start the server
app.listen(app.get("port"), function () { console.log("Express server listening on port " + app.get("port")); });
And then will work .. i'm not sure why but after it happen few time i learn the lesson .
This solved the problem for me
var bodyParser = require('body-parser');
var app=express();
app.use(bodyParser.urlencoded());
app.use(bodyParser.json());
Hope this help
Just ran into the same issue. It looks like I resolved my problem by moving my code to map routes after the urlencoded line. I am now seeing req.body in the post.
app.use(bodyParser.urlencoded({ extended: true }));
// Map routes
var controllers = require("./controllers");
controllers.init(app);
If you're using urlencoded with { extended:false }
, req.body
will return the unparsed raw string from the form categoryName=test
. Meaning req.body.categoryName
will be undefined.
Try passing true so it can parse the form data using the qs module.
app.use(bodyParser.urlencoded({
extended: true
}));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With