fm722 fm722 - 7 days ago 5
Node.js Question

Why does node.js attach a string value in my array to another object in the array as true?

I'm not sure why this is happening, but could use some input.

I have an object attached to the body of a POST request through jquery ajax. The object is similar to this example:

var dogData = {breeds: [{Dog: "Golden Retriever"}, "Rottweiler"]}


The AJAX request is this:

$.ajax({
type: "POST",
url: "api/dog",
data: dogData,
})


On my server using Express + bodyparser:

app.post('/dogs', function(req, res){console.log(req.body)})


When I console.log the object:

{breeds: [{Dog: "Golden Retriever", Rottweiler: true}]}


I want the same object that I initially started out with to be returned from the server. Can someone explain why the string is attached to the previous object along with a boolean value?

Answer

use jsonparser on your server and make your post with json content

$.ajax({
        type: "POST",
        url: "api/dog",
        data: JSON.stringify(dogData),
        contentType: 'application/json; charset=utf-8'
       })

Body parser parses urlencoded form data.

When you send your data it will be converted to:

breeds[0][Dog]=Golden+Retriever&breeds[Rottweiler];

When bodyparser parse it, because of there is no value on Rottweiler and it exists, it will be converted to "true"