16

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

terminal

JCollier
  • 1,102
  • 2
  • 19
  • 31
Karina
  • 195
  • 1
  • 2
  • 11

6 Answers6

27

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

Varun Bhalla
  • 415
  • 6
  • 8
6

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?

Sandy Garrido
  • 168
  • 5
  • 21
  • 1
    You're right. But since now "body-parser deprecated undefined extended", only the first option (app.use(bodyParser.urlencoded({extended: true}));) is proper. The second option (app.use(bodyParser.urlencoded());) will give a warning, although it can still be used. – William Hou Dec 17 '19 at 21:12
3

Try this it worked with me

let payLoad = [];
Reflect.ownKeys(req.body).forEach(key => {
          payLoad = JSON.parse(key);
        });
2

You can use the following:

console.log(JSON.stringify(req.body, null, 2));

The last argument controls the number of spaces used for indentation.

ulyssesrr
  • 71
  • 5
1

You can use something like this:

Reflect.ownKeys(obj).forEach(key => {
  console.log(key + ":" + obj[key]);
});
adiga
  • 34,372
  • 9
  • 61
  • 83
andrea-f
  • 1,045
  • 9
  • 23
0

This should help resolve the issue JSON.stringify(Object)