我有一个控制器没有发回响应。
@Controller('/foo')
export class FooController {
@Post()
public async getBar(@Body() body: DTO, @Res() res) {
const response = await this.doSomething(body);
return response;
}
}
Run Code Online (Sandbox Code Playgroud)
我不得不使用以下res.send方法:
@Controller('/foo')
export class FooController {
@Post()
public async getBar(@Body() body: DTO, @Res() res) {
const response = await this.doSomething(body);
res.send(response);
}
}
Run Code Online (Sandbox Code Playgroud)
Lea*_*dro 12
原因是@Res() res参数。如果删除它,响应将正确发送:
@Controller('/foo')
export class FooController {
@Post()
public async getBar(@Body() body: DTO) {
const response = await this.doSomething(body);
return response;
}
}
Run Code Online (Sandbox Code Playgroud)
@Res({ passthrough: true })如果您希望使用 Nest 方式发送响应,则必须使用。
如果您想像 Express 框架一样发送响应@Res()并添加代码res.status(200).send()
https://docs.nestjs.com/controllers
警告 Nest 会检测处理程序何时使用 @Res() 或 @Next(),这表明您已选择特定于库的选项。如果同时使用两种方法,则该单一路线的标准方法将自动禁用,并且将不再按预期工作。要同时使用这两种方法(例如,通过注入响应对象以仅设置 cookie/标头,但仍将其余部分留给框架),您必须在 @Res({ passthrough: true }) 装饰器。