req.body.hasOwnProperty is not a function

how to reproduce this issue?

router.post('/', function(req, res, next) {
	console.log(req.body.hasOwnProperty('asdf'));
});
  • run the server
  • use postman to send a POST request with a couple of body parameters.
  • you’ll get:
<!DOCTYPE html>
<html>
    <head>
        <title></title>
        <link rel="stylesheet" href="/stylesheets/style.css">
    </head>
    <body>
        <h1>req.body.hasOwnProperty is not a function</h1>
        <h2></h2>
        <pre></pre>
    </body>
</html>

req.body.hasOwnProperty is not a function

Why this happening? is this behaviour expected?

Author: Fantashit

2 thoughts on “req.body.hasOwnProperty is not a function

  1. Well, assuming that the above was the only change, then the answer would be that req.body is the result of Node.js core querystring module’s parse function (https://nodejs.org/dist/latest-v6.x/docs/api/querystring.html#querystring_querystring_parse_str_sep_eq_options), which doesn’t inherit from Object:

    Note: The object returned by the querystring.parse() method does not prototypically extend from the JavaScript Object. This means that the typical Object methods such as obj.toString(), obj.hasOwnProperty(), and others are not defined and will not work.

  2. @wesleytodd Ahh! missed it 😅

    So this is the expected behavior. (it would be awesome if it wasn’t. lol )

    Now I can

    router.post('/', function(req, res, next) {
      req.body = JSON.parse(JSON.stringify(req.body));
      console.log(req.body.hasOwnProperty('asdf'));
    });

    to fix the issue.

Comments are closed.