nest.js-学习记录:5、Put、Delete请求和Url路径参数

import { Body, Controller, Delete, Get, Param, Post, Put, Query } from '@nestjs/common';
import { ApiOperation, ApiProperty, ApiTags } from '@nestjs/swagger';

// 标识创建帖子的参数详情
class createPostDto{
    @ApiProperty({description:'帖子标题'})
    title:string
    @ApiProperty({description:'帖子内容'})
    content:string
}

@Controller('posts')
@ApiTags('帖子')
export class PostsController {
  @Get()
  @ApiOperation({summary:'显示博客列表'})
  index() {
    return [
      {id:1111},
      {id:13},
      {id:14},
      {id:1},
      {id:37},
      {id:26},
    ];
  }

  @Post()
  @ApiOperation({summary:"创建帖子"})
  // 获取post请求的数据用@Body()装饰器获取数据
  create(@Body() Body:createPostDto){
    return{
      success:true
    }
  }

  @Get(':id')
  @ApiOperation({summary:"帖子详情"})
  //此处用@Param('id')获取id的值
  detail(@Param('id') id:string){
    return{
    //获取的id值
      id:id,
      title:'aaaaa'
    }
  }
	//put请求
  @Put(':id')
  @ApiOperation({summary:'编辑帖子详情'})
   //此处用@Param('id')获取id的值,并且因为编辑和新建帖子需要的数据一样所以,
   //也使用createPostDto的规则约束。
  update(@Param('id') id:string,@Body() body:createPostDto){
    return {
      success:true
    }
  }
  //Delete请求
  @Delete(':id')
  @ApiOperation({summary:'删除帖子'})
  remove(@Param('id') id:string){
    return{
      success:true
    }

  }
}

示例
在这里插入图片描述

### 解决Nest.js后端404 Not Found错误 在处理Nest.js后端路径更新时遇到的`404 Not Found`错误,通常是因为请求的目标路由未被正确定义或匹配。以下是可能导致此问题的原因以及解决方案: #### 1. 路由定义不正确 如果目标路径`seniorHealthData`未在控制器中明确定义,则会触发`404 Not Found`错误。确保已创建相应的模块控制器,并注册到应用程序实例。 ```typescript // senior-health-data.controller.ts import { Controller, Get } from '@nestjs/common'; @Controller('seniorHealthData') export class SeniorHealthDataController { @Get() getSeniorHealthData() { return { message: 'Senior Health Data Retrieved Successfully!' }; } } ``` 上述代码片段展示了如何通过装饰器`@Controller('seniorHealthData')`来设置基础路径[^3]。 #### 2. 应用程序全局前缀配置 检查是否存在全局路径前缀影响实际访问地址。例如,在主文件`app.module.ts`中设置了如下内容: ```typescript // main.ts import { NestFactory } from '@nestjs/core'; import { AppModule } from './app.module'; async function bootstrap() { const app = await NestFactory.create(AppModule); app.setGlobalPrefix('api'); // 设置全局API前缀 await app.listen(3000); } bootstrap(); ``` 在这种情况下,完整的URL应为`http://localhost:3000/api/seniorHealthData`而不是仅限于`/seniorHealthData`[^4]。 #### 3. 动态参数缺失 当尝试传递动态参数而未适配相应逻辑时也可能引发该类异常。比如期望获取特定ID下的健康数据记录却忘记声明变量占位符: ```typescript // senior-health-data.controller.ts import { Param } from '@nestjs/common'; @Controller('seniorHealthData') export class SeniorHealthDataController { @Get(':id') getSeniorHealthById(@Param('id') id: string) { return `This would return data for ID ${id}`; } } ``` 这里利用了`@Param()`注入服务提取URL中的`:id`部分作为函数形参传入[^5]。 #### 4. 中间件拦截行为干扰正常流程执行 某些自定义中间件可能会阻止默认响应机制从而造成误解现象发生。务必审查所有加载至项目内的第三方库或者自行编写的过滤规则是否合理合法。 --- ### 示例代码调整后的完整结构 假设我们希望实现一个简单的RESTful API用于查询老年人健康管理信息列表及其详情页展示功能的话可以按照下面方式重构整个工程架构设计思路: ```typescript // app.module.ts import { Module } from '@nestjs/common'; import { AppController } from './app.controller'; import { AppService } from './app.service'; import { SeniorHealthDataModule } from './modules/senior-health-data/senior-health-data.module'; @Module({ imports: [SeniorHealthDataModule], controllers: [AppController], providers: [AppService], }) export class AppModule {} ``` ```typescript // senior-health-data.controller.ts import { Body, Controller, Delete, Get, HttpCode, HttpStatus, Param, Post, Put, UsePipes, ValidationPipe } from '@nestjs/common'; import { CreateSeniorHealthDto } from '../dto/create-senior-health.dto'; import { UpdateSeniorHealthDto } from '../dto/update-senior-health.dto'; import { SeniorHealthDataService } from '../services/senior-health-data.service'; @Controller('seniorHealthData') export class SeniorHealthDataController { constructor(private readonly seniorHealthDataService: SeniorHealthDataService) {} @Post() @UsePipes(new ValidationPipe()) create(@Body() createSeniorHealthDto: CreateSeniorHealthDto): any { return this.seniorHealthDataService.create(createSeniorHealthDto); } @Get() findAll(): any[] { return this.seniorHealthDataService.findAll(); } @Get(':id') findOne(@Param('id') id: number): any { return this.seniorHealthDataService.findOne(id); } @Put(':id') update(@Param('id') id: number, @Body() updateSeniorHealthDto: UpdateSeniorHealthDto): any { return this.seniorHealthDataService.update(id, updateSeniorHealthDto); } @Delete(':id') remove(@Param('id') id: number): void { this.seniorHealthDataService.remove(id); } } ``` 以上即为针对当前场景下推荐的最佳实践方案之一[^6]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

言只 石皮

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值