新手入门NestJS(十二)- 控制器所有请求方式实例

这里记录下使用Nest.js中,在控制器中如何添加所有请求方式的方法

第一种请求方式Get

1
2
3
4
5
6
7
8
9
@Get()
findAll() {
return 'This action will return all dogs';
}

@Get(':id')
findOne(@Param('id') id: string) {
return `This action will return one ${id} dog`;
}

第二种请求方式Post

1
2
3
4
@Post()
create(@Body() createDogDto: CreateDogDto) {
return `This action will add a dog`;
}

第三种请求方式Put

1
2
3
4
@Put(':id')
update(@Param('id') id: string, @Body() updateDogDto: UpdateDogDto) {
return `This action will update a dog`;
}

第四种请求方式Delete

1
2
3
4
@Delete(':id')
remove(@Param('id') id: string) {
return `This action will remote a dog`;
}

完整的代码如下

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
30
31
32
33
34
35
36
37
38
39
import {
Body,
Controller,
Delete,
Get,
Param,
Post,
Put,
} from '@nestjs/common';
import { CreateDogDto } from 'src/create-dog.dto';
import { UpdateDogDto } from 'src/update-dog.dto';

@Controller('dogs')
export class DogsController {
@Get()
findAll() {
return 'This action will return all dogs';
}

@Get(':id')
findOne(@Param('id') id: string) {
return `This action will return one ${id} dog`;
}

@Post()
create(@Body() createDogDto: CreateDogDto) {
return `This action will add a dog`;
}

@Put(':id')
update(@Param('id') id: string, @Body() updateDogDto: UpdateDogDto) {
return `This action will update a dog`;
}

@Delete(':id')
remove(@Param('id') id: string) {
return `This action will remote a dog`;
}
}