5

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 ?

Kawd
  • 4,122
  • 10
  • 37
  • 68

4 Answers4

4

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);
});
Samundra Khatri
  • 997
  • 1
  • 9
  • 18
2

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

contentType: "application/json"
Amith
  • 730
  • 6
  • 22
1

just remove this content type from client request header

 'Content-Type':'application/x-www-form-urlencoded'
Hisham
  • 1,279
  • 1
  • 17
  • 23
0

You can get the KEY using the VALUE like so:

function getKeyByValue(object, value) {
  return Object.keys(object).find(key => object[key] === value);
}
Uche Azinge
  • 682
  • 1
  • 8
  • 14