You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

新手求教:如何在NestJS GraphQL项目中添加POST JSON请求

在NestJS GraphQL项目中添加携带JSON请求体的POST接口步骤

1. 创建REST控制器

GraphQL项目默认以GraphQL模块为主,但添加REST接口只需创建标准的NestJS控制器:

  • 在项目src目录下新建rest文件夹,创建post.controller.ts文件
  • 导入@nestjs/common中的Controller、Post、Body装饰器,编写控制器类:
    import { Controller, Post, Body } from '@nestjs/common';
    
    @Controller('api/posts') // 定义接口前缀,最终请求路径为 http://localhost:3000/api/posts
    export class PostController {
      @Post() // 标记这是POST请求
      handlePostRequest(@Body() requestBody: any) {
        // 这里编写你的业务逻辑,比如调用服务层处理数据
        return { status: 'success', receivedData: requestBody };
      }
    }
    

2. 注册控制器到根模块

找到项目根模块src/app.module.ts,将新建的控制器加入模块的controllers数组:

import { Module } from '@nestjs/common';
import { GraphQLModule } from '@nestjs/graphql';
import { ApolloDriver, ApolloDriverConfig } from '@nestjs/apollo';
import { PostController } from './rest/post.controller'; // 导入控制器

@Module({
  imports: [
    GraphQLModule.forRoot<ApolloDriverConfig>({
      driver: ApolloDriver,
      autoSchemaFile: 'schema.gql', // 你的GraphQL配置
    }),
  ],
  controllers: [PostController], // 注册控制器
})
export class AppModule {}

3. 测试接口可用性

  • 启动项目:npm run start:dev
  • 用curl或Postman发送POST请求:
    curl -X POST http://localhost:3000/api/posts \
    -H "Content-Type: application/json" \
    -d '{"name": "测试数据", "value": 123}'
    
  • 正常情况下会收到响应:{"status": "success", "receivedData": {"name": "测试数据", "value": 123}}

4. 进阶:用DTO规范请求体(推荐)

为了保证请求体的格式合法性,可使用DTO(数据传输对象)结合校验:

  • 在src/rest/dtos目录下创建create-post.dto.ts:
    import { IsString, IsNotEmpty, IsNumber } from 'class-validator';
    
    export class CreatePostDto {
      @IsString()
      @IsNotEmpty()
      name: string;
    
      @IsNumber()
      value: number;
    }
    
  • 在main.ts中启用全局校验管道,让校验生效:
    import { ValidationPipe } from '@nestjs/common';
    import { NestFactory } from '@nestjs/core';
    import { AppModule } from './app.module';
    
    async function bootstrap() {
      const app = await NestFactory.create(AppModule);
      app.useGlobalPipes(new ValidationPipe()); // 全局启用校验
      await app.listen(3000);
    }
    bootstrap();
    
  • 修改控制器,用DTO替代any类型:
    import { Controller, Post, Body } from '@nestjs/common';
    import { CreatePostDto } from './dtos/create-post.dto';
    
    @Controller('api/posts')
    export class PostController {
      @Post()
      handlePostRequest(@Body() requestBody: CreatePostDto) {
        return { status: 'success', receivedData: requestBody };
      }
    }
    

内容的提问来源于stack exchange,提问作者Divyansh Goenka

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.22 09:55:05