jameel
jameel

Reputation: 51

Why can't we send data as an javascript object instead of a JSON object?

I am a newbie to expressjs. I have made this application in it and when I pass data in JSON format via POSTMAN then it returns me the data. Good but when I send data as a javascript object in request body then it doesn't work i.e. body empty.

Code:

var express= require('express')
var eApp= express();

eApp.use(express.json());

var collection= [{id: 1, name:'Hunain1'},
                 {id: 2, name:'Hunain2'},
                 {id: 3, name:'Hunain4'}
                ];

eApp.post('/api/hunain/', (req, res) => 
{
    //var col= collection.find(col => col.id === parseInt(req.params.id));

    if(req.body === "")
    {
        res.status(404).send("sorry, object is empty");     
    }
    else
    {
        var collObj= {id: collection.length, name: req.body.name};
        collection.push(collObj);

        res.send(collObj);
    }
});

//console.log('nodeapp4 has been accessed') 

eApp.listen(100, () => console.log('nodeapp4 is listening to your requests'));

Request in JSON:

{
    "id": 3,
    "name": "Bose"
}

returns

{
    "id": 4,
    "name": "Bose"
}

this is when I select application/Json in postman

but when I select Javascript and write this in body:

 {
    id : "2",
    name : "Bose"
}

then it returns only id but no name i.e. body sends as an empty, why?

Upvotes: 2

Views: 1364

Answers (1)

Tsvetan Ganev
Tsvetan Ganev

Reputation: 8856

JSON is a data transfer format. It's sole purpose is to be compact, easy to serialize/deserialize and programming language independent (there are JSON libraries for all the popular languages out there).

JavaScript objects are specific to JavaScript runtimes (they can't be used by a Python or C# server) and are unsafe for data transfer because they can include behaviour (methods). Imagine someone sends you this malicious JS object:

{
  firstName: (function () {
    var fs = require('fs');
    // proceed to delete all files in the directory...
  })()
}

If you were on a Node.js environment and the runtime parses such malicious object, you would expose yourself to enormous security threats.

Upvotes: 2

Related Questions