-5

Brand new to javascript. Used to strong typed Object oriented languages like Java and C#.

I am looking over some existing express javascript code that handles a request body.

const username = req.body.username

From what I understand username is a field passed in json. How is there a field on body that is called username already?

I was expected to see something like this...

const username = req.body['username']

Can anyone clarify what is going on here?

Scorb
  • 1,654
  • 13
  • 70
  • 144
  • That's just another way of accessing properties from object – Naren Dec 02 '21 at 18:15
  • 4
    this: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Property_accessors - MDN is your reference for anything JavaScript. Google "MDN _anything here_" to get instant answers. – Randy Casburn Dec 02 '21 at 18:15
  • @Scorb Out of interest, why did you expect the `body` property to be accessed with the dot notation but the `username` property to be accessed with the bracket notation? Is that something from the previous languages? – Matt Dec 03 '21 at 00:05
  • Does this answer your question? [JavaScript property access: dot notation vs. brackets?](https://stackoverflow.com/questions/4968406/javascript-property-access-dot-notation-vs-brackets) – Matt Dec 03 '21 at 00:10

1 Answers1

1

How is there a field on body that is called username already?

Because the middleware that processes the incoming HTTP request put it there.

I was expected to see something like this...

The dot or bracket notation is different syntax for accessing the same property.

Matt
  • 68,711
  • 7
  • 155
  • 158
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335