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

相关推荐
林恒smileZAZ1 天前
Vue<前端页面版本检测>
前端·javascript·vue.js
码事漫谈1 天前
当AI开始“思考”:我们是否真的准备好了?
前端·后端
Unity粉末状在校生1 天前
Git解决fatal: Could not read from remote repository.的问题
git
许杰小刀1 天前
ctfshow-web文件包含(web78-web86)
android·前端·android studio
少年攻城狮1 天前
Obsidian系列---【如何使用obsidian同步到git?】
git
我是Superman丶1 天前
Element UI 表格某行突出悬浮效果
前端·javascript·vue.js
恋猫de小郭1 天前
你的代理归我了:AI 大模型恶意中间人攻击,钱包都被转走了
前端·人工智能·ai编程
xiaokuangren_1 天前
前端css颜色
前端·css
Huanzhi_Lin1 天前
关于V8/MajorGC/MinorGC——性能优化
javascript·性能优化·ts·js·v8·新生代·老生代
hoiii1871 天前
C# 基于 LumiSoft 实现 SIP 客户端方案
前端·c#