You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

NestJS自定义Pipe无法修改值?问题排查求助

NestJS自定义Pipe返回NaN的原因及修复

你的自定义Pipe无法正常工作有两个核心问题:

1. Pipe转换逻辑错误

transform方法的核心是处理传入的参数值(value),但你现在错误地对metadata.data执行了parseInt:

  • metadata.data是@Query('content', CustomPipe)里的第一个参数,也就是字符串'content',对'content'执行parseInt自然返回NaN。
  • 正确的做法是对value(请求中content参数的实际值)进行转换。

2. 请求参数格式错误

你的请求URL里content参数带了双引号:content="1234",此时value的值是字符串'"1234"':

  • parseInt('"1234"')会返回NaN,因为字符串首字符是双引号,不是有效数字起始符。
  • 正确的请求参数应该去掉双引号:content=1234。

修正后的Pipe代码

import { PipeTransform, Injectable, ArgumentMetadata, BadRequestException } from '@nestjs/common';

@Injectable()
export class CustomPipe implements PipeTransform {
  transform(value: any, metadata: ArgumentMetadata) {
    // 传入基数10确保十进制转换,避免意外的八进制解析
    const parsedValue = parseInt(value, 10);
    // 增加验证逻辑,转换失败时抛出异常
    if (isNaN(parsedValue)) {
      throw new BadRequestException('content参数必须是有效的数字');
    }
    return parsedValue;
  }
}

修正后的请求URL

http://localhost:3001/123?content=1234

此时控制台会输出:

content 1234
number
parseint  1234

内容的提问来源于stack exchange,提问作者hacoo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.12 10:10:34