fm722 fm722 - 1 year ago 83
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:

type: "POST",
url: "api/dog",
data: dogData,

On my server using Express + bodyparser:'/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 Source

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

        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:


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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download