2

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?

4
  • You're probably not JSON.parse()ing the JSON string back into an object so you can access the name property. So only the id returns, since it does not depend on the body. Maybe express should do that for you automatically, but don't know the exact flag to set in express. Commented Aug 8, 2018 at 11:40
  • the id field is a number in your collection, not a string Commented Aug 8, 2018 at 11:41
  • @Shilly: I did but didn't work Commented Aug 8, 2018 at 12:06
  • @mast3rd3mon: that's not the reason. Problem is something else. Commented Aug 8, 2018 at 12:06

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.