Ammar Khan
Ammar Khan

Reputation: 2585

Nodejs- Req.body undefined in post with express 4.x

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>

Upvotes: 11

Views: 34086

Answers (6)

Wanderson Elias
Wanderson Elias

Reputation: 11

I am use this:

const app = express(); app.use(bodyParser.urlencoded({ extended: true })); app.use(express.json()); but verify if your POSTMAN, for he can be the problem

Upvotes: 0

Muhammad Soliman
Muhammad Soliman

Reputation: 23756

As body-parser module is used to parse the body and urls, it should be called before any call to "req.body..."

var bodyParser = require("body-parser");
///////req.body is undefined here
//extended: false means you are parsing strings only (not parsing images/videos..etc)
app.use(bodyParser.urlencoded({extended: false});
///////you req.body is working here (module below is using req.body)
app.use("/", module);
app.post('/newCategory', function (req,res) {
     var categoryName = req.body.categoryName;
});

Upvotes: 1

ackuser
ackuser

Reputation: 5879

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

Upvotes: 7

Teodor
Teodor

Reputation: 1305

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
  1. 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 .

Upvotes: 4

user3926346
user3926346

Reputation: 121

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

Upvotes: 12

Ben Fortune
Ben Fortune

Reputation: 32118

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

Upvotes: 2

Related Questions