1

我想通过坐标获取位置。我从一个简单的 DTO 开始

export class GetLocationByCoordinatesDTO {
    @IsNumber()
    @Min(-90)
    @Max(90)
    public latitude: number;

    @IsNumber()
    @Min(-180)
    @Max(180)
    public longitude: number;
}

和这个 API 端点

@Get(':latitude/:longitude')
public getLocationByCoordinates(@Param() { latitude, longitude }: GetLocationByCoordinatesDTO): Promise<Location> {
  // ...
}

为了测试这个端点,我调用了这个 url

本地主机:3000/locations/0/0

不幸的是我得到了以下回复

{
    "statusCode": 400,
    "message": [
        "latitude must not be greater than 90",
        "latitude must not be less than -90",
        "latitude must be a number conforming to the specified constraints",
        "longitude must not be greater than 180",
        "longitude must not be less than -180",
        "longitude must be a number conforming to the specified constraints"
    ],
    "error": "Bad Request"
}

有人知道如何解决这个问题吗?我希望它会通过。

似乎 url 参数被认为是字符串,但我怎样才能将它们解析为数字呢?

4

1 回答 1

5

这是众所周知的问题,您可以在github issue上找到更多内容。

您的问题的解决方案是Number像这样在 DTO 中显式转换类型:

import { Min, Max, IsNumber } from 'class-validator';
import { Type } from 'class-transformer';

export class GetLocationByCoordinatesDTO {
  @IsNumber()
  @Type(() => Number)
  @Min(-90)
  @Max(90)
  public latitude: number;

  @IsNumber()
  @Type(() => Number)
  @Min(-180)
  @Max(180)
  public longitude: number;
}

class-transformer如果你想让它工作,你需要安装:

npm i class-transformer -S

其他一切都应该没问题。

于 2020-04-13T12:50:16.333 回答