Search code examples
routescontrollernestjsurl-parameters

NestJS - Controller - Get(':id') returned 404


I have the following code in my orders.controller.ts file:

@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);
  }
}

I want to test the Get(':id') route with the following url: http://localhost:3000/orders?id=1

but I still have a 404 error:

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

Solution

  • to handle 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);
      }
    }
    

    otherwise you should make a GET /orders/1 request.