【NestJS】swagger快速接入

1.安装swagger

$ npm install --save @nestjs/swagger swagger-ui-express


//如果使用fastify,则必须安装fastify-swagger而不是swagger-ui-express:
$ npm install --save @nestjs/swagger fastify-swagger

2.Bootstrap启动配置

import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { DocumentBuilder, SwaggerModule } from '@nestjs/swagger';

async function bootstrap() {
  const app = await NestFactory.create(AppModule);

  const options = new DocumentBuilder()
    .setTitle('测试接口')
    .setDescription('接口文档')
    .setVersion('1.0')
    .build();
  const document = SwaggerModule.createDocument(app, options);
  SwaggerModule.setup('api-docs', app, document);

  await app.listen(3000);
}
bootstrap();

3.DTO示例

import { ApiProperty } from "@nestjs/swagger";

/** */
export class LoginDto {
    @ApiProperty({ 
        required: true,
        description:'登录名'
    })
    readonly loginId: string;
    @ApiProperty({ 
        required: true,
        description:'密码'
    })
    readonly pwd: string;
}

// export interface SchemaObject {
//     nullable?: boolean;
//     discriminator?: DiscriminatorObject;
//     readOnly?: boolean;
//     writeOnly?: boolean;
//     xml?: XmlObject;
//     externalDocs?: ExternalDocumentationObject;
//     example?: any;
//     examples?: any[];
//     deprecated?: boolean;
//     type?: string;
//     allOf?: (SchemaObject | ReferenceObject)[];
//     oneOf?: (SchemaObject | ReferenceObject)[];
//     anyOf?: (SchemaObject | ReferenceObject)[];
//     not?: SchemaObject | ReferenceObject;
//     items?: SchemaObject | ReferenceObject;
//     properties?: Record<string, SchemaObject | ReferenceObject>;
//     additionalProperties?: SchemaObject | ReferenceObject | boolean;
//     description?: string;
//     format?: string;
//     default?: any;
//     title?: string;
//     multipleOf?: number;
//     maximum?: number;
//     exclusiveMaximum?: boolean;
//     minimum?: number;
//     exclusiveMinimum?: boolean;
//     maxLength?: number;
//     minLength?: number;
//     pattern?: string;
//     maxItems?: number;
//     minItems?: number;
//     uniqueItems?: boolean;
//     maxProperties?: number;
//     minProperties?: number;
//     required?: string[];
//     enum?: any[];
// }

 

4.控制器示例


import { Body, Controller, Get, Param, Post, Query } from '@nestjs/common'
import { ApiTags, ApiOperation, ApiQuery, ApiParam } from '@nestjs/swagger';
import { LoginDto } from '../../models/dto/customer.dto'

// import { Request } from 'express'

@Controller('customer')
@ApiTags('用户模块')
export class CustomerController {

    @Post('login')
    @ApiOperation({ summary: '登录' })
    // login(@Req() request: Request): boolean {
    login(@Body() reqBody: LoginDto): boolean {
        // console.log('query', query)
        console.log('reqBody', reqBody)

        // const query = request.query
        const loginId = reqBody.loginId
        const pwd = reqBody.pwd

        if (pwd === '123') {
            return true
        }

        return false
    }

    @Get('/getUserName/:id')
    @ApiOperation({ summary: '获取用户名' })
    @ApiParam({ name: 'id', description: '用户id', required: false })
    getUserName(@Param('id') id: string): string {
        return "这个是用户名" + id
    }

    @Get('getUserName2')
    @ApiOperation({ summary: '获取用户名' })
    @ApiQuery({ name: 'id', description: '用户id', required: false })
    getUserName2(@Query('id') id: string): string {
        return "这个是用户名" + id
    }


}

 

5.实际效果

npm rn start

http://localhost:3000/api-docs/

 

 

 

 

 

 

 

### 解决NestJSSwagger配置不生效的问题 在Nest应用中集成`@nestjs/swagger`模块时,如果遇到Swagger UI页面无法正常显示API文档的情况,可能由多种因素引起。以下是排查和解决问题的方法: #### 1. 安装依赖包 确认已安装必要的npm包,包括但不限于`@nestjs/swagger`以及其同伴库`swagger-ui-express`。 ```bash npm install @nestjs/swagger swagger-ui-express --save ``` #### 2. 配置全局前缀 确保应用程序设置了统一的路由前缀,在main.ts文件内添加如下代码片段[^1]: ```typescript async function bootstrap() { const app = await NestFactory.create(AppModule); // 设置全局路径前缀 app.setGlobalPrefix('api'); await app.listen(3000); } bootstrap(); ``` #### 3. 创建并注册Swagger模块 于根模块AppModule中引入SwaggerModule,并定义相应的选项对象用于定制化生成的OpenAPI规格说明文档: ```typescript import { Module } from '@nestjs/common'; import { APP_INTERCEPTOR } from '@nestjs/core'; import { ConfigService } from './config/config.service'; // 导入Swagger相关类 import { SwaggerModule, DocumentBuilder } from '@nestjs/swagger'; @Module({ imports: [ /* ... */ // 注册Swagger中间件 SwaggerModule.forRootAsync({ useFactory: async () => ({ title: 'My Application', description: 'This is my awesome application!', version: '1.0', explorer: true, // 如果存在全局前缀,则在此处指定 basePath: '/api' }), inject: [ConfigService], }) ], }) export class AppModule {} ``` #### 4. 添加控制器描述符 为了使特定端点能够被正确识别并加入到最终呈现给用户的交互界面里去,需为各个Controller及其方法加上适当注解,比如@ApiTags(), @ApiOperation(), etc. ```typescript import { Controller, Get } from '@nestjs/common'; import { ApiTags, ApiResponse, Operation } from '@nestjs/swagger'; @Controller('example') @ApiTags('Example Endpoints') // 给整个controller打标签 export class ExampleController { constructor(private readonly exampleService: ExampleService) {} @Get() @Operation({ summary: 'Fetches an example response.' }) // 描述具体操作行为 @ApiResponse({ status: 200, description: 'The found record' }) findAll(): string { return this.exampleService.findAll(); } } ``` #### 5. 检查拦截器影响 某些情况下自定义的响应拦截器可能会干扰默认返回结构,进而导致Swagger解析失败。例如提供的AllResponseInterceptor会改变原始HTTP Response Body格式,这与预期不符。建议移除此类组件或将它们调整至不影响标准JSON输出的形式[^5]。 通过上述措施通常能有效解决大多数关于NestJS环境下Swagger插件失效的情形;当然实际场景下还可能存在其他潜在原因等待探索发现。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

程序员查理

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

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

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

打赏作者

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

抵扣说明:

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

余额充值