【NestJS】为什么return不返回客户端?

在 NestJS 中,当你使用了 @Res()(或 @Response())装饰器时,NestJS 会进入**"库原生模式"(Library-specific mode)**。

原因分析

一旦你在路由处理函数中注入了 @Res(),NestJS 就失去了对响应流的自动控制权。此时,NestJS 不再理会函数的 return ,它会认为你将手动处理响应(例如通过调用 res.send()res.json())。

在你提供的代码中:

  1. 你使用了 @Res() res: Response
  2. 你写了 return ret;
  3. 由于 NestJS 在等待你手动调用 res 的方法来结束请求,而你一直没调用,请求就会一直挂起(Pending),直到浏览器或服务器超时。

解决方案

你有三种方式可以解决这个问题:

方案一:手动调用 res.send()res.json() (推荐用于需要精细控制响应的情况)

既然你已经引入了 res 对象,就直接使用它来发送数据:

typescript 复制代码
@Get('confirm-email')
async confirmEmail(@Query('code') code: string, @Res() res: Response) {
  let ret = {
    code: RETCODE.EMAIL_CONFIRMATION_FAILED,
    access_token: null,
    message: 'Error 9004',
  };

  const userCode = await this.loginService.getCode(code, 1);
  if (!userCode) {
    console.log('User code not found');
    return res.status(200).json(ret); // 使用 res.json() 发送响应
  }
  
  // 注意:其他逻辑路径也必须通过 res 发送响应
}
方案二:使用 passthrough: true (最推荐:既想用 res 又想用 return)

如果你只想用 res 来设置一些东西(比如 Cookie、Header),但仍然希望由 NestJS 来处理 return 的返回值,可以设置 passthrough 参数:

typescript 复制代码
@Get('confirm-email')
async confirmEmail(@Query('code') code: string, @Res({ passthrough: true }) res: Response) {
  let ret = {
    code: RETCODE.EMAIL_CONFIRMATION_FAILED,
    access_token: null,
    message: 'Error 9004',
  };

  const userCode = await this.loginService.getCode(code, 1);
  if (!userCode) {
    return ret; // 此时 return 生效了,NestJS 会自动包装成 JSON 发送
  }
}
方案三:移除 @Res() (最简洁)

如果你在函数体里根本没用到 res 对象(比如只是为了定义类型却没调用它的方法),直接删掉它。这是 NestJS 的推荐做法,它会自动处理 return 的对象。

typescript 复制代码
@Get('confirm-email')
async confirmEmail(@Query('code') code: string) { // 移除 @Res
  let ret = {
    code: RETCODE.EMAIL_CONFIRMATION_FAILED,
    access_token: null,
    message: 'Error 9004',
  };

  const userCode = await this.loginService.getCode(code, 1);
  if (!userCode) {
    return ret; // 正常工作
  }
}

总结

在 NestJS 中,一旦用了 @Res(),你就得对响应负责 。如果不调用 res.send() 或设置 passthrough: true,客户端将永远等不到响应。

相关推荐
何中应17 小时前
使用SSH地址拉取远程仓库代码报下面的错误
git
子兮曰17 小时前
OpenClaw入门:从零开始搭建你的私有化AI助手
前端·架构·github
何中应17 小时前
Git本地仓库命令补充
git
吴仰晖17 小时前
使用github copliot chat的源码学习之Chromium Compositor
前端
1024小神17 小时前
github发布pages的几种状态记录
前端
sun00770019 小时前
执行repo sync -c -d -j4以后,提交未git push的代码看不到了。要怎么恢复?
git
不像程序员的程序媛19 小时前
Nginx日志切分
服务器·前端·nginx
Daniel李华19 小时前
echarts使用案例
android·javascript·echarts
北原_春希19 小时前
如何在Vue3项目中引入并使用Echarts图表
前端·javascript·echarts
JY-HPS19 小时前
echarts天气折线图
javascript·vue.js·echarts