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
Object with null prototype and its purpose If you create an object in JavaScript - it has some methods by default, such as toString(), keys() or hasOwnProperty(). But that is true when you create an object based on default Object. You can create also an object that lacks them - to save resources maybe?
The value null represents the intentional absence of any object value. It is one of JavaScript's primitive values and is treated as falsy for boolean operations.
getPrototypeOf() The Object. getPrototypeOf() method returns the prototype (i.e. the value of the internal [[Prototype]] property) of the specified object.
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With