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?
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.