Node/Mongoose/BodyParser not correctly accepting urlencoded POST requests

Node/Mongoose/BodyParser not correctly accepting urlencoded POST requests
0

#1

I’ve been mostly following these two (suspiciously) similar tutorials to learn back end web development.

However, when I get to the part where you accept a post request in order to edit the database, I’m running into a problem. I believe I have body-parser set up correctly

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

and I believe that I’m correctly handling the request.

var itemRouter = router.route('/items');

//Creating an endpoint for POSTS /api/beers
itemRouter.post(function(req, res){
    console.log(req.body); //This always returns {}
    var newItem = new Item();
    newItem.name = req.body.name; //These two lines of code are replaced in the working JSON version
    newItem.quantity = req.body.name; //These two lines of code are replaced in the working JSON version

    //Saves the new item to the database
    newItem.save(function(err){
        if(err) {
            res.send(err);
        }
        //sends a response

        res.json({
            message: 'Item added to the database!',
            data: newItem
        });
    });
});

However, clearly something is going wrong. I’m using postman to send requests to my server with {Content-Type : “application/x-www-form-urlencoded” }, but it isn’t correctly getting that information as the console.log I have commented always returns an empty object showing that no information from the body is making it to that point.

I am able to correctly handle JSON formatted inputs by replacing the marked two lines with

newItem.name= req.body[0].value;
newItem.quantity = req.body[1].value;

However, I would like to figure this issue out and learn from it rather than hack a workaround. I’ve attached the complete source code at the gist below. Thanks in advance for all the help!

This is what I’m getting in my database: {“id”:“5a9e0d9f5ecb6825b8d68544”,"_v":0}

This is what I am hoping to get in my database: {“id”:“5a9dff951281120fac21aa18”,“name”:“Pepperoni Pizza”,“quantity”:8,"_v":0}


#2

Let’s write a bit of middleware to check that the post data is coming in:

function testMiddleware(req, res, next) {
    if(req.method !== "POST") return next();
    var body = '';
    req.on('data', function(data) {
        body += data;
    });
    req.on('end', function() {
        var jsonData = JSON.parse(body);
        console.log("****POST DATA****");
        console.log(jsonData);
        console.log("*****************");
        next();
    });
}

I haven’t tested this, but you should be able to just copypaste that into your code (don’t leave it in after testing because a bad person could blow up your server with a large file). If it works, then I take all the credit. If it breaks, then it was all Kif’s fault.

Then add this to your app before you use bodyParser:

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

That will tell you if your app is receiving the POST data.


#3

Thanks for the help! The server errors out with

undefined:1

SyntaxError: Unexpected end of JSON input

when I attempt to make a POST request


#4

Of course it does! Try taking out app.use(bodyParser.urlencoded({ extended:true}));


#5

Even after commenting out that line I’m getting the same error.


#6

Alright, forget I wrote that piece of code. I should have tested it before having you try it. I’ll suffer some debugging myself and see if I can’t get an answer.


#7

Ok, so I’ve played around with it and was able to reproduce your problem and find the solution. Make sure that you’re sending the request as “Form URL encoded”, or something like that. You’re probably using “Multipart Form”. I don’t use Postman, so I don’t know exactly what the option is called, but you’re looking for the option with both “form” and “url” in the name.


#8

I am sending it as x-www-form-urlencoded


#9

Double check that you’ve got the correct option selected in the body section of Postman. It’s not enough to just have the correct header. I copied and pasted your code and I’m able to get it to work with no modification, so it definitely works.


#10

A restart and update of Postman fixed the issue. I’m not sure why exactly it wasn’t working in the first place, but thanks so much for all of the help!


#11

What does the * mean in console.log(***************) ? if it means something of importance, how do I get it?


#12

It’s console.log("*************");

It’s just a string of asterisks.

Also, please don’t revive threads that have had no activity for 7 months.