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)
}
}
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
bodyParserimport 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
Most helpful comment
@posabsolute @ivanproskuryakov You have to add
bodyParserimport 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')
});