Routing-controllers: @Body() empty with @Controller?

Created on 2 Jun 2020  路  4Comments  路  Source: typestack/routing-controllers

Hi guys,

Whenever I use @Controller I seems to not receive JSON body content. It works when I use @Jsoncontroller, am I missing anything?

I use createExpressApp, I tried version 0.8 and 0.9 and express 4 and 3. @Controller always return {} while Jsoncontroller works.

@Controller('/templates')
export class TemplateController {
    @Post('/:name')
    public getTemplate(@Param('name') templateName: string, @Body() body: any): string {
        return this.templateService.render(templateName, body)
    }
}

Most helpful comment

@posabsolute @ivanproskuryakov You have to add bodyParser

import express from "express";
import bodyParser from 'body-parser';

server.use(bodyParser.json());
server.use(bodyParser.urlencoded({extended: true}));

useExpressServer(server, {});

server.listen(PORT, function () {
console.log('Example app listening on port 3000')
});

All 4 comments

Hey @posabsolute, I just tested @JsonController and @Controller the same behavior confirmed.
However, @Req() req: any and req.body returns the data.

@posabsolute @ivanproskuryakov You have to add bodyParser

import express from "express";
import bodyParser from 'body-parser';

server.use(bodyParser.json());
server.use(bodyParser.urlencoded({extended: true}));

useExpressServer(server, {});

server.listen(PORT, function () {
console.log('Example app listening on port 3000')
});

Hi @antowkabond, thanks, this is working indeed.

@posabsolute @ivanproskuryakov You have to add bodyParser

import express from "express";
import bodyParser from 'body-parser';

server.use(bodyParser.json());
server.use(bodyParser.urlencoded({extended: true}));

useExpressServer(server, {});

server.listen(PORT, function () {
console.log('Example app listening on port 3000')
});

Since I was using createExpressServer to create my server, adding this implementation alone didn't solve it, so I had to create a bare express server and add the configuration to useExpressServer

  const server = express();

  server.use(bodyParser.json());
  server.use(bodyParser.urlencoded({ extended: true }));

  useExpressServer(server, {
    controllers: [join(__dirname, 'app', 'controllers', '*.ts')],
  });

  server.listen(process.env.PORT || 3333, () => {
    console.log(`Server listening on port ${process.env.PORT}`);
  });

And now it works

Was this page helpful?
0 / 5 - 0 ratings

Related issues

mlarsson picture mlarsson  路  5Comments

humbertowoody picture humbertowoody  路  4Comments

azaslonov picture azaslonov  路  5Comments

kkorus picture kkorus  路  4Comments

AleskiWeb picture AleskiWeb  路  4Comments