request.body seems always undefined inside middleware
@JsonController('/my-controller/')
export class MyController {
@Post('/')
@UseBefore((request: any, _response: any, next?: (err?: any) => any): any => {
console.log('body ====>', request.body);
if (next) {
next();
}
})
public async postCallback(@Body() things: any): Promise<any> {
// Some code here
}
}
It's by design - route's before middlewares runs before multer or body-parser that are related to the route decorators @Files() or @Body(). You should mount global middleware to have access to it's result everywhere.
@19majkel94 thx man, i saw that on google.
I was thinking @Body decorator was simply extracting the data after bodyParser.
Big mistake shame on me!
Now i'm doing this and working like a charm.
Is it the best approach?
@Post('/')
@UseBefore((request: any, response: any, next?: (err?: any) => any): any => {
const json: RequestHandler = bodyParser.json();
json(request, response, () => {
// Do something here with request.body
if (next instanceof Function) {
next();
}
});
})
You can chain middlewares like in pure express 馃槈
function myMiddleware(req, res, next) {
console.assert(req.body !== undefined);
next();
}
@JsonController('/my-controller/')
export class MyController {
@Post('/')
@UseBefore(bodyParser.json(), myMiddleware)
public async postCallback(@Body() things: any): Promise<any> {
// Some code here
}
}
Please reopen if you have more questions 馃槈
This issue has been automatically locked since there has not been any recent activity after it was closed. Please open a new issue for related bugs.
Most helpful comment
You can chain middlewares like in pure express 馃槈
Please reopen if you have more questions 馃槈