Thursday, 6 September 2018

req.body.anything is undefined despite using body-parser

I'm trying to build an API that receives a POST req to create a user but I am getting undefined errors for all of my req.body requests. My app is set up like this (simplified for brevity):User controller that gets called by Express Router in my user routes file/controllers/user.jsuserController.addUser = function(req, res) { let user = new User(); user.username = req.body.username; user.first_name = req.body.first_name; user.last_name = req.body.last_name; user.email = req.body.email; user.type = req.body.user_type // This returns undefined as does all other req.body keys console.log("REQ.BODY.EMAIL IS: " + req.body.email); } User Route File:/routes/user.js - requires user controller aboverouter.post('/user/create', userController.addUser); Entry Point to App: all routes and controllers work per my tests except where req.body.* is usedindex.js - main app fileapp.use(bodyParser.urlencoded({ extended: true })); app.use(bodyParser.json()); app.use('/api', routes); I have looked through the Express documentation, StackOverflow and Reddit posts, and other random sites but can't figure out where I'm missing the "connection" for the req.body. Any advice would be greatly appreciated! Let me know if you'd like further clarification.

Submitted September 06, 2018 at 09:31PM by evsoul

No comments:

Post a Comment