routing-controllers icon indicating copy to clipboard operation
routing-controllers copied to clipboard

fix: body in middleware is undefined. I have bodyParser

Open Zekhap opened this issue 2 months ago • 0 comments

Description

I'm trying to print the request.body in my console from the middleware but its undefined I've googled everywhere and tested allot of things, yet i cant seem to find my answer.

Minimal code-snippet showcasing the problem

@Service()
@Middleware({ type: "before" })
export class DemoMiddleware implements ExpressMiddlewareInterface {
  async use(request: any, response: any, next: (err?: any) => any): Promise<any> {
    console.log("-DemoMiddleware-");

    console.log(request.body); //Is undefined
    next();
  }
}

@JsonController("/")
export class DemoController {
    @Post("test")
    demoPost(@Body() params: DemoResponse, @Res() response: Response) {
        console.log("-DemoPost-");

        return response.status(200).json({ message: "i got post", params: params });
    }
}
export class DemoResponse {
    username: string;
    password: string;
}

createExpressServer({
    controllers: [DemoController],
    middlewares: [
        bodyParser.json(),
        bodyParser.urlencoded({ extended: true }),
        DemoMiddleware
    ],
    routePrefix: '/api',
}).listen(3000);

Expected behavior

I expect to get the json that i posted

package.json "body-parser": "^1.20.2", "reflect-metadata": "^0.2.2", "routing-controllers": "^0.10.4", "class-transformer": "^0.5.1", "class-validator": "^0.14.1", "typedi": "^0.10.0",

Zekhap avatar May 08 '24 22:05 Zekhap