10

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

2 Answers 2

13

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;
  }
}
Sign up to request clarification or add additional context in comments.

2 Comments

Incase you need to modify the response object, see this warning from Nest: 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.
In my case, I removed the @Res() but all GET method don't return any response body. Do you guys know why it happen?
8

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.