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

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

第一种请求方式Get

@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

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

第三种请求方式Put

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

第四种请求方式Delete

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

完整的代码如下

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`;
  }
}