Leandro
Leandro

Reputation: 1522

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);
  }
}

Upvotes: 10

Views: 6515

Answers (2)

Gustavo Contreiras
Gustavo Contreiras

Reputation: 570

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.

Upvotes: 8

Leandro
Leandro

Reputation: 1522

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;
  }
}

Upvotes: 13

Related Questions