Search code examples
javascriptnode.jsexpressbody-parser

req.body is undefined, but body-parser is initialized


All the time I get an error calling req.body is undefined, but I included body-parser in my middlewares. I use it like it should be used, at least I think I do because I get the warning

'body-parser' is deprecated

Is it correct initialization of body-parser? Why do I get that error?

app.use(bodyParser.json())

EDIT

I just added bodyParser to my route middleware, and now it works. Can someone explain why it work only that way, when none of tutorials do it like this?

doesn't work:

app.use('/api/users', authRoute)

works

app.use('/api/users', bodyParser.json(), authRoute)

EDIT2

It was because I defined middlewares below route middlewares, I didn't know order matters, maybe not only me so I leave this edit


Solution

  • So the problem was I defined middlewares below route middlewares, I didn't know order matters, maybe not only me so I leave this solution for someone who's going to get this problem in a future