'NestJS: My controller doesn't send the response

I had a controller that didn't send the response back.

@Controller('/foo')
export class FooController {
  @Post()
  public async getBar(@Body() body: DTO, @Res() res) {
    const response = await this.doSomething(body);
    return response;
  }
}

I had to use the res.send method:

@Controller('/foo')
export class FooController {
  @Post()
  public async getBar(@Body() body: DTO, @Res() res) {
    const response = await this.doSomething(body);
    res.send(response);
  }
}


Solution 1:[1]

The cause was the @Res() res parameter. If you delete it, the response will be sent correctly:

@Controller('/foo')
export class FooController {
  @Post()
  public async getBar(@Body() body: DTO) {
    const response = await this.doSomething(body);
    return response;
  }
}

Solution 2:[2]

You have to use @Res({ passthrough: true }) if you want the response to be send using the Nest way.

If you want to send the response like on Express framework use @Res() and add code res.status(200).send()

https://docs.nestjs.com/controllers

WARNING Nest detects when the handler is using either @Res() or @Next(), indicating you have chosen the library-specific option. If both approaches are used at the same time, the Standard approach is automatically disabled for this single route and will no longer work as expected. To use both approaches at the same time (for example, by injecting the response object to only set cookies/headers but still leave the rest to the framework), you must set the passthrough option to true in the @Res({ passthrough: true }) decorator.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Leandro
Solution 2 Gustavo Contreiras