Routing-controllers: @UseBefore middleware do not returns any body

Created on 7 Feb 2018  路  4Comments  路  Source: typestack/routing-controllers

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
}

}
question

Most helpful comment

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 馃槈

All 4 comments

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.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

azaslonov picture azaslonov  路  5Comments

GBeushausen picture GBeushausen  路  5Comments

OysteinAmundsen picture OysteinAmundsen  路  3Comments

davidquintard picture davidquintard  路  4Comments

AleskiWeb picture AleskiWeb  路  4Comments