【问题标题】:NestJS - Controller - Get(':id') returned 404NestJS - 控制器 - Get(':id') 返回 404
【发布时间】:2021-08-23 08:34:25
【问题描述】:

我的 orders.controller.ts 文件中有以下代码:

@Controller('orders')
export class OrdersController {
  constructor(private ordersService: OrdersService) {}

  @Get(':id')
  async getOrderById(@Param('id', ParseIntPipe) id: number): Promise<Order> {
    return this.ordersService.getOrderById(id);
  }
}

我想使用以下 url 测试 Get(':id') 路由:http://localhost:3000/orders?id=1

但我仍然有 404 错误:

{
     "statusCode": 404,
     "message": "Cannot GET /orders?id=1",
     "error": "Not Found"
}

【问题讨论】:

  • 应该是@Controller(/orders) 和@Get(/:id)
  • @CharchitKapoor 您的解决方案不起作用
  • 对不起,您的请求 url 应该是 /orders/1
  • 我一定是累了……非常感谢!

标签: routes controller nestjs url-parameters


【解决方案1】:

处理GET /orders?id=1:

@Controller('orders')
export class OrdersController {
  constructor(private ordersService: OrdersService) {}

  @Get()
  async getOrderById(@Query('id') id?: string): Promise<Order> {
    return this.ordersService.getOrderById(id);
  }
}

否则您应该发出GET /orders/1 请求。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-01-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多