user2272048
user2272048

Reputation:

Express.js : POST data as KEY of a req.body object instead of VALUE of req.body?

from the client I'm doing :

$.ajax({
        url: '/create',
        type: 'POST',
        data: JSON.stringify({
            theme: "somevalue",
            snippet: {
                name: "somename",
                content: "somevalue"
            }
        }), 
        complete: function (response)
        {

        }
    });

on the server ( node.js/express.js ) I'm doing :

var app = express();
app.use(cookieParser());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));
.......
... 
app.post('/create', function (req, res)
{
   var dataReceived = req.body;
});

I expected the value of dataReceived to be :

{
   "theme" : "somevalue",
   "snippet" : {
     "name": "somename",
     "content" : "somevalue"
   } 
}

Instead the value of dataReceived was :

{ 
 '{"theme":"somevalue","snippet":"name":"somename","content":"somevalue"}}': '' 
}

This is really weird and I can't find what I'm doing wrong. Any ideas?

from the BodyParser module documentation :

bodyParser.urlencoded(options)

Returns middleware that only parses urlencoded bodies. This parser accepts only UTF-8 encoding of the body and supports automatic inflation of gzip and deflate encodings.

A new body object containing the parsed data is populated on the request object after the middleware (i.e. req.body). This object will contain key-value pairs, where the value can be a string or array (when extended is false), or any type (when extended is true).

Is this related to my problem ?

Upvotes: 5

Views: 14576

Answers (4)

Amith
Amith

Reputation: 767

Set this content-type on client side ajax call if you are going to use JSON.stringify:

contentType: "application/json"

Upvotes: 2

Uche Azinge
Uche Azinge

Reputation: 692

You can get the KEY using the VALUE like so:

function getKeyByValue(object, value) {
  return Object.keys(object).find(key => object[key] === value);
}

Upvotes: 0

Hisham
Hisham

Reputation: 1316

just remove this content type from client request header

 'Content-Type':'application/x-www-form-urlencoded'

Upvotes: 1

Samundra Khatri
Samundra Khatri

Reputation: 987

Remove Stringify in your client side

$.ajax({
        url: '/create',
        type: 'POST',
        data: {
            theme: "somevalue",
            snippet: {
                name: "somename",
                content: "somevalue"
            }
        }, 
        complete: function (response)
        {

        }
    });

or parse it again in server side

app.post('/create', function (req, res)
{
   var dataReceived = JSON.parse(req.body);
});

Upvotes: 3

Related Questions