Number 通过从 Angular 客户端到 NestJS 服务器的 Http 请求变成字符串

Number Turns to String over Http Request from Angular Client to NestJS Server

通过从 Angular 客户端到 NestJS 服务器的 Http 请求,数字变成字符串:

我通过 firstIndex: number 从我的 Angular 客户端到我的 NestJS 服务器的 GET http 请求的参数传递。我到处都把它定义为一个数字。在我的服务函数 firstIndex: number 的参数中。从服务器端抓取它时 @Query('firstIndex') firstIndex: number 但是当我尝试使用它时,我 运行 遇到了问题。当我记录 typeof firstIndex 时,它以字符串形式出现。我必须使用 const firstInd = Number(firstIndex).

将其转换为数字

我假设这只是与 http 请求本身的性质有关,但我很想知道具体原因。

我在开始使用 NestJS 和路由时遇到了类似的问题。

然后,在浏览文档和一些开源 NestJS API 项目时,我找到了多种方法来解决这个问题。

  1. 您可以利用 ValidationPipe 将负载自动转换为您想要的类型。

有两种方法。

第一个是在您的控制器方法级别应用 ValidationPipe

@Get()
@UsePipes(new ValidationPipe({ transform: true })) // <--- Add this line
getRows(
  @Query('firstIndex') firstIndex: number,
  @Query('limit') limit: number,
  @Query('sorts') sorts: string
){
  console.log(typeof firstIndex === 'number'); // true
  console.log(typeof limit === 'number'); // true
  console.log(typeof sorts === 'string'); // true
}

另一种在全局级别应用 ValidationPipe 行为的方法。

这就是您在 NestJS 应用程序实例化文件中的做法:

app.useGlobalPipes(
  new ValidationPipe({
    transform: true,
  }),
);

ValidationPipe@UsePipes() 装饰器是从 @nestjs/common 包中导入的)

您可以在 NestJS Transform payload objects doc 中阅读更多相关信息。

  1. 第二种方法是显式转换值的类型。

这就是完成它的方法:

@Get()
getRows(
  @Query('firstIndex', ParseIntPipe) firstIndex: number, // <-- Added ParseIntPipe
  @Query('limit', ParseIntPipe) limit: number, // <-- Added ParseIntPipe
  @Query('sorts') sorts: string
){
  console.log(typeof firstIndex === 'number'); // true
  console.log(typeof limit === 'number'); // true
  console.log(typeof sorts === 'string'); // true
}

ParseIntPipe 是从 @nestjs/common 包导入的)

如你所见,在这里,我在 @Query 装饰器中传递了另一个参数,即 Pipe 。它会将值解析为整数。

您可以阅读有关 NestJS Transform Explicit conversion doc here 的更多信息。

外部链接: