Is there a way to get rid of the [Object: null prototype]
in the terminal so it will only display {title: 'book'}
?
I was doing console.log(req.body);
in node/express.js
This additional [Object: null prototype] problem occurs in Node when we console.log some object which has null prototype...
which simply means that the object won't have it's inbuilt methods... like => .toString() or .hasOwnProperty() etc...
const obj1 = Object.create(null);
obj1['key'] = 'SomeValue' ;
console.log(obj1);
>> [Object: null prototype] { 'key' : 'SomeValue' }
const obj2 = {};
obj2['key'] = 'SomeValue' ;
console.log(obj2);
>> { 'key' : 'SomeValue' }
when we set extended in app.use(urlencoded{ ... }) option to true => the URL encoded data is parsed by qs library ,
when we set it to false , it's parsed by query-string library...
in query-string library ( https://nodejs.org/api/querystring.html#querystring_querystring_parse_str_sep_eq_options )
it clearly states that
The object returned by the querystring.parse() method does not prototypically inherit from the JavaScript Object. This means that typicalObject methods such as obj.toString(), obj.hasOwnProperty(), and others are not defined and will not work.
or in other words , they have null prototype...
that's why in case of {extended:false} when we console.log(req.body) => output contains additional [Object: null prototype] in the beginning...
For other differences , use
This sounds like you're using {extended: false}
within .urlencoded() when you're parsing the body. Try removing it or changing to true.
Go back a few steps and edit which may look something like this
app.use(bodyParser.urlencoded({extended: true}));
or just simply
app.use(bodyParser.urlencoded());
To find out more about the extended option, read the docs or someone here has answered it well - What does 'extended' mean in express 4.0?
Try this it worked with me
let payLoad = [];
Reflect.ownKeys(req.body).forEach(key => {
payLoad = JSON.parse(key);
});
You can use the following:
console.log(JSON.stringify(req.body, null, 2));
The last argument controls the number of spaces used for indentation.