Every object in JS has a toString () method?

enter image description here

enter image description here

If so, then why is this error occurring? The req.body object req.body not null or undefined , as shown.

I use node-inspector to debug my express.js application, this snapshot was taken in Chrome Developer Tools .

Express configuration:

app.use(express.bodyParser())

Thanks to your comments, now I found req.body is undefined , but a new question is how to make toString work again? I want req.body.toString() return a string as shown below:

enter image description here

How to rewrite the correct toString method?

I tried delete undefined toString , nothing good. Cm:

enter image description here

+7
source share
1 answer

Every object in JS has a toString () method?

No. Only those that inherit it from Object.prototype (as all ordinary objects do) or define it themselves (or inherit from their custom prototype).

You can create such unusual objects using Object.create(null) . You can also give a regular object its own toString property that obscures the inherited property and is not a function (for example, {toString:0} ), but I think that would cause an explicit error.

In your case, it seems that the request parser bodyParser() used by bodyParser() really (really) creates objects without prototypes in order to avoid distortion of .constructor.prototype when using such parameters. See Qs pullrequest # 58 and urgent issue 1636: Does Bodyparser not set object.prototype? (suggesting an update).

How to reassign the correct toString method?

You can simply assign any function, for example,

 req.body.toString = function() { return "Hi, I'm a request body"; }; 

but probably you want a standard one:

 req.body.toString = Object.prototype.toString; 

Other options would be to override the prototype through the non-standard __proto__ property ( req.body.__proto__ = Object.prototype ) or simply apply a stand-alone function to an object instead of creating it using a method, such as Object.prototype.toString.call(req.body) .

+15
source

Source: https://habr.com/ru/post/953254/


All Articles