expressjs / body-parser

Node.js body parsing middleware

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

urlencoded not passing body to next middleware, but do to final controller

marik22312 opened this issue · comments

Hi, I've encountered some weird behavior from the URL encoded parser...
it seems that the body is not passed to my next middleware, but It's passed to the final controller.

in example sending the following data:

name='test'

to this route:

// test.ctrl.ts
export const myController = (req: Request, res: Response, next: NextFunction) => {
  console.log(req.body) // prints { name: 'test' }
}

// routes.ts
router.post('/', bodyParser.urlencoded({ extended: true }), (req, res, next) => {
  console.log(req.body) //prints {}
  next()
}, myController);

note that in the middleware, it prints an empty object, and in the controller, I get the body correctly...

I do not completely understand why and how this is possible...
any suggestions?

Hi @marik22312 I'm sorry you're having an issue. I have never heard of such behavior before so have no idea what would be going on. Since you didn't provide complete code to reproduce the issue, I tried to make some:

const bodyParser = require('body-parser')
const express = require('express')

const app = express()

function myController(req, res, next) {
    console.log('== controller')
    console.log(req.body)
    res.end()
}

app.post('/', bodyParser.urlencoded({ extended: true }), (req, res, next) => {
    console.log('== middleware')
    console.log(req.body)
    next()
}, myController)

app.listen(3000)

Unfortunately that did not reproduce the issue (curl -i http://localhost:3000/ -d'foo=bar'):

$ node app.js
== middleware
{ foo: 'bar' }
== controller
{ foo: 'bar' }

If you can provide the complete code I can run in order to reproduce the issue you're having, I would love to have a look.

Hey @dougwilson ! thank you for the fast reply!
unfortunately, I'm unable to reproduce this issue...
I've played around with it for a while, seems that it's somehow related to the https://github.com/expressjs/multer package.

anyway,
here's the client request
https://github.com/marik22312/radiosavta-backoffice/blob/feature/create-program/src/services/programs.service.ts#L81

funny thing is I have the exact same request at
https://github.com/marik22312/radiosavta-backoffice/blob/feature/create-program/src/services/users.service.ts#L29

and it works the same,
any middleware in between doesn't receive the body, but the final controller does.

ill play around with this a little more today until ill be able to reproduce this constantly

@marik22312 did you managed to solve the issue? 🤔

@UlisesGascon hey, yes! The issue was between the seat and the screen... I had a multer Middleware which also parsed the body... So naturally, body parser couldn't get the body from a formData request...

Closing the issue...

Glad to hear that @marik22312! Thanks for provide the details and close the issue 👍