Skip to content
On this page

@Get

@Get 是 NestJS 框架中的一个装饰器,用于将控制器方法映射到 HTTP GET 请求。这个装饰器是由 @nestjs/common 模块提供的。通过使用 @Get 装饰器,可以指定该方法处理特定路径上的 GET 请求。

基本用法

typescript
import { Controller, Get } from '@nestjs/common';

@Controller('users')
export class UsersController {
  @Get()
  findAll(): string {
    return 'This action returns all users';
  }
}

1
2
3
4
5
6
7
8
9
10

在这个示例中:

  • @Controller('users')UsersController 类定义为一个控制器,并将其基本路径设为 users
  • @Get() 装饰器将 findAll 方法映射到 GET /users 请求。

处理带参数的 GET 请求

可以通过在 @Get 装饰器中指定路径参数来处理带参数的 GET 请求。

typescript
import { Controller, Get, Param } from '@nestjs/common';

@Controller('users')
export class UsersController {
  @Get(':id')
  findOne(@Param('id') id: string): string {
    return `This action returns user #${id}`;
  }
}

1
2
3
4
5
6
7
8
9
10

在这个示例中:

  • @Get(':id') 装饰器将 findOne 方法映射到 GET /users/:id 请求,其中 :id 是一个路由参数。
  • @Param('id') 装饰器用于提取请求路径中的 id 参数。

处理带查询参数的 GET 请求

可以通过使用 @Query 装饰器来提取查询参数。

typescript
import { Controller, Get, Query } from '@nestjs/common';

@Controller('users')
export class UsersController {
  @Get()
  findAll(@Query('age') age: string): string {
    return `This action returns users of age ${age}`;
  }
}

1
2
3
4
5
6
7
8
9
10

在这个示例中:

  • @Query('age') 装饰器用于提取请求 URL 中的查询参数 age
  • 请求 GET /users?age=25 将调用 findAll 方法,并传递 age 参数的值。

组合使用路径和查询参数

可以同时使用路径参数和查询参数来处理更复杂的请求。

typescript
import { Controller, Get, Param, Query } from '@nestjs/common';

@Controller('users')
export class UsersController {
  @Get(':id')
  findOne(@Param('id') id: string, @Query('includePosts') includePosts: boolean): string {
    return `This action returns user #${id} with includePosts=${includePosts}`;
  }
}

1
2
3
4
5
6
7
8
9
10

在这个示例中:

  • @Get(':id') 装饰器将 findOne 方法映射到 GET /users/:id 请求。
  • @Param('id')@Query('includePosts') 分别用于提取路径参数和查询参数。

完整示例

以下是一个完整的示例,展示了如何在控制器中使用 @Get 装饰器处理不同的 GET 请求:

typescript
import { Controller, Get, Param, Query } from '@nestjs/common';

@Controller('users')
export class UsersController {
  // 处理没有参数的 GET 请求
  @Get()
  findAll(): string {
    return 'This action returns all users';
  }

  // 处理带路径参数的 GET 请求
  @Get(':id')
  findOne(@Param('id') id: string): string {
    return `This action returns user #${id}`;
  }

  // 处理带查询参数的 GET 请求
  @Get()
  findByAge(@Query('age') age: string): string {
    return `This action returns users of age ${age}`;
  }

  // 处理带路径和查询参数的 GET 请求
  @Get(':id/details')
  findOneWithDetails(@Param('id') id: string, @Query('includePosts') includePosts: boolean): string {
    return `This action returns user #${id} with includePosts=${includePosts}`;
  }
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29

在这个示例中:

  • findAll 方法处理没有参数的 GET 请求。
  • findOne 方法处理带路径参数的 GET 请求。
  • findByAge 方法处理带查询参数的 GET 请求。
  • findOneWithDetails 方法处理带路径和查询参数的 GET 请求。

总结

@Get 是一个用于处理 HTTP GET 请求的装饰器,通过它可以轻松地将控制器方法映射到特定的请求路径。通过结合使用 @Param@Query 等装饰器,可以灵活地处理各种类型的 GET 请求。使用 @Get 装饰器,可以使代码更加模块化和易于维护。

沪ICP备20006251号-1