【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,客户端将永远等不到响应。

相关推荐
爱上妖精的尾巴10 小时前
8-5 WPS JS宏 match、search、replace、split支持正则表达式的字符串函数
开发语言·前端·javascript·wps·jsa
小温冲冲10 小时前
通俗且全面精讲单例设计模式
开发语言·javascript·设计模式
Vermouth_0011 小时前
git clone的时候提示access denied
git
意法半导体STM3211 小时前
【官方原创】FDCAN数据段波特率增加后发送失败的问题分析 LAT1617
javascript·网络·stm32·单片机·嵌入式硬件·安全
为什么不问问神奇的海螺呢丶11 小时前
n9e categraf redis监控配置
前端·redis·bootstrap
云飞云共享云桌面11 小时前
推荐一些适合10个SolidWorks设计共享算力的服务器硬件配置
运维·服务器·前端·数据库·人工智能
咔咔一顿操作11 小时前
轻量无依赖!autoviwe 页面自适应组件实战:从安装到源码深度解析
javascript·arcgis·npm·css3·html5
刘联其11 小时前
.net也可以用Electron开发跨平台的桌面程序了
前端·javascript·electron
韩曙亮11 小时前
【jQuery】jQuery 选择器 ④ ( jQuery 筛选方法 | 方法分类场景 - 向下找后代、向上找祖先、同级找兄弟、范围限定查找 )
前端·javascript·jquery·jquery筛选方法
前端 贾公子11 小时前
Node.js 如何处理 ES6 模块
前端·node.js·es6