Reputation: 195
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
Upvotes: 16
Views: 26984
Reputation: 219
This should help resolve the issue JSON.stringify(Object)
Upvotes: 0
Reputation: 259
Try this it worked with me
let payLoad = [];
Reflect.ownKeys(req.body).forEach(key => {
payLoad = JSON.parse(key);
});
Upvotes: 3
Reputation: 425
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
what the difference between qs and querystring
Upvotes: 28
Reputation: 1055
You can use something like this:
Reflect.ownKeys(obj).forEach(key => {
console.log(key + ":" + obj[key]);
});
Upvotes: 1
Reputation: 196
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?
Upvotes: 6
Reputation: 71
You can use the following:
console.log(JSON.stringify(req.body, null, 2));
The last argument controls the number of spaces used for indentation.
Upvotes: 2