从小白到精通——NestJS企业级后端框架全攻略
NestJS 是一个基于 TypeScript 的。NestJS 推荐使用 DTO 对输入数据进行验证。NestJS 的一切功能都存在于模块中。NestJS 通过构造函数自动注入依赖。Nest 项目结构高度模块化。中间件可用于日志、认证等逻辑。RESTful API 服务。WebSocket 实时通信。全局安装 Nest CLI。在入口文件启用全局验证。查看可视化接口文档。GraphQL 网关。服
一、认识 NestJS
NestJS 是一个基于 TypeScript 的 企业级 Node.js 框架,融合了 OOP(面向对象编程)、FP(函数式编程) 和 FRP(响应式编程) 思想。
它的核心理念是:
模块化 + 控制反转 + 装饰器驱动开发 + 高可维护性架构。
NestJS 特别适合构建:
-
RESTful API 服务
-
微服务架构
-
GraphQL 网关
-
WebSocket 实时通信
-
企业后端系统
二、安装与环境准备
-
全局安装 Nest CLI
npm install -g @nestjs/cli
-
创建项目
nest new my-nest-app
-
启动开发服务
cd my-nest-app npm run start:dev
打开浏览器访问 http://localhost:3000 即可看到:
Hello World!
三、项目结构
my-nest-app/ ├── src/ │ ├── app.controller.ts # 控制器(路由层) │ ├── app.service.ts # 服务层(业务逻辑) │ ├── app.module.ts # 根模块 │ └── main.ts # 程序入口 └── package.json
Nest 项目结构高度模块化。
四、创建控制器 Controller
控制器负责接收请求、返回响应。
nest generate controller user
user.controller.ts
import { Controller, Get, Post, Body, Param } from '@nestjs/common'; @Controller('user') export class UserController { private users = []; @Get() getAll() { return this.users; } @Get(':id') getUser(@Param('id') id: number) { return this.users.find(u => u.id == id); } @Post() addUser(@Body() body: any) { const newUser = { id: this.users.length + 1, ...body }; this.users.push(newUser); return newUser; } }
运行后访问:
-
GET /user -
POST /user { "name": "张三" }
五、服务层 Service
服务层负责业务逻辑。
nest generate service user
user.service.ts
import { Injectable } from '@nestjs/common'; @Injectable() export class UserService { private users = []; findAll() { return this.users; } findOne(id: number) { return this.users.find(u => u.id === id); } create(user: any) { const newUser = { id: this.users.length + 1, ...user }; this.users.push(newUser); return newUser; } }
user.controller.ts
import { Controller, Get, Post, Param, Body } from '@nestjs/common'; import { UserService } from './user.service'; @Controller('user') export class UserController { constructor(private userService: UserService) {} @Get() getAll() { return this.userService.findAll(); } @Get(':id') getOne(@Param('id') id: number) { return this.userService.findOne(+id); } @Post() add(@Body() body: any) { return this.userService.create(body); } }
六、模块化结构
NestJS 的一切功能都存在于模块中。
user.module.ts
import { Module } from '@nestjs/common'; import { UserController } from './user.controller'; import { UserService } from './user.service'; @Module({ controllers: [UserController], providers: [UserService], }) export class UserModule {}
app.module.ts
import { Module } from '@nestjs/common'; import { UserModule } from './user/user.module'; @Module({ imports: [UserModule], }) export class AppModule {}
七、DTO 数据传输对象
NestJS 推荐使用 DTO 对输入数据进行验证。
npm install class-validator class-transformer
create-user.dto.ts
import { IsString, IsInt, MinLength } from 'class-validator'; export class CreateUserDto { @IsString() @MinLength(2) name: string; @IsInt() age: number; }
user.controller.ts
import { Body, Controller, Post } from '@nestjs/common'; import { CreateUserDto } from './dto/create-user.dto'; import { UserService } from './user.service'; @Controller('user') export class UserController { constructor(private userService: UserService) {} @Post() create(@Body() dto: CreateUserDto) { return this.userService.create(dto); } }
八、全局数据验证管道
在入口文件启用全局验证。
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();
九、使用中间件
中间件可用于日志、认证等逻辑。
logger.middleware.ts
import { Injectable, NestMiddleware } from '@nestjs/common'; @Injectable() export class LoggerMiddleware implements NestMiddleware { use(req: Request, res: Response, next: Function) { console.log(`[${req.method}] ${req.url}`); next(); } }
app.module.ts
import { MiddlewareConsumer, Module, NestModule } from '@nestjs/common'; import { LoggerMiddleware } from './logger.middleware'; import { UserModule } from './user/user.module'; @Module({ imports: [UserModule], }) export class AppModule implements NestModule { configure(consumer: MiddlewareConsumer) { consumer.apply(LoggerMiddleware).forRoutes('*'); } }
十、依赖注入(DI)
NestJS 通过构造函数自动注入依赖。
@Injectable() export class EmailService { sendEmail(to: string, subject: string) { console.log(`发送邮件到:${to},主题:${subject}`); } } @Injectable() export class UserService { constructor(private emailService: EmailService) {} create(user: any) { this.emailService.sendEmail(user.email, '欢迎注册'); } }
十一、配置环境变量
npm install @nestjs/config
app.module.ts
import { ConfigModule } from '@nestjs/config'; @Module({ imports: [ConfigModule.forRoot()], }) export class AppModule {}
使用方式:
import { ConfigService } from '@nestjs/config'; constructor(private configService: ConfigService) { const dbHost = this.configService.get('DB_HOST'); }
.env
DB_HOST=localhost DB_PORT=3306
十二、连接数据库(TypeORM + MySQL)
npm install @nestjs/typeorm typeorm mysql2
app.module.ts
import { TypeOrmModule } from '@nestjs/typeorm'; @Module({ imports: [ TypeOrmModule.forRoot({ type: 'mysql', host: 'localhost', port: 3306, username: 'root', password: '123456', database: 'nestdb', autoLoadEntities: true, synchronize: true, }), ], }) export class AppModule {}
user.entity.ts
import { Entity, Column, PrimaryGeneratedColumn } from 'typeorm'; @Entity() export class User { @PrimaryGeneratedColumn() id: number; @Column() name: string; @Column() age: number; }
user.module.ts
import { TypeOrmModule } from '@nestjs/typeorm'; import { User } from './user.entity'; @Module({ imports: [TypeOrmModule.forFeature([User])], })
user.service.ts
import { Injectable } from '@nestjs/common'; import { InjectRepository } from '@nestjs/typeorm'; import { Repository } from 'typeorm'; import { User } from './user.entity'; @Injectable() export class UserService { constructor(@InjectRepository(User) private repo: Repository<User>) {} findAll() { return this.repo.find(); } create(user: Partial<User>) { return this.repo.save(user); } }
十三、异常处理与拦截器
import { ExceptionFilter, Catch, ArgumentsHost, HttpException } from '@nestjs/common'; @Catch(HttpException) export class HttpErrorFilter implements ExceptionFilter { catch(exception: HttpException, host: ArgumentsHost) { const ctx = host.switchToHttp(); const res = ctx.getResponse(); const status = exception.getStatus(); res.status(status).json({ statusCode: status, message: exception.message, timestamp: new Date().toISOString(), }); } }
main.ts
app.useGlobalFilters(new HttpErrorFilter());
十四、守卫(Guard)实现权限控制
import { CanActivate, ExecutionContext, Injectable } from '@nestjs/common'; @Injectable() export class AuthGuard implements CanActivate { canActivate(context: ExecutionContext): boolean { const req = context.switchToHttp().getRequest(); return req.headers.token === 'secret123'; } }
controller.ts
@UseGuards(AuthGuard) @Get() getAll() { return this.userService.findAll(); }
十五、全局拦截器
import { Injectable, NestInterceptor, ExecutionContext, CallHandler } from '@nestjs/common'; import { map } from 'rxjs/operators'; @Injectable() export class TransformInterceptor implements NestInterceptor { intercept(context: ExecutionContext, next: CallHandler) { return next.handle().pipe(map(data => ({ code: 0, data }))); } }
main.ts
app.useGlobalInterceptors(new TransformInterceptor());
十六、Swagger 自动文档
npm install @nestjs/swagger swagger-ui-express
main.ts
import { DocumentBuilder, SwaggerModule } from '@nestjs/swagger'; const config = new DocumentBuilder() .setTitle('NestJS API') .setDescription('自动生成的API文档') .setVersion('1.0') .build(); const document = SwaggerModule.createDocument(app, config); SwaggerModule.setup('docs', app, document);
访问 http://localhost:3000/docs 查看可视化接口文档。
十七、WebSocket 实时通信
npm install @nestjs/websockets @nestjs/platform-socket.io
chat.gateway.ts
import { WebSocketGateway, SubscribeMessage, MessageBody } from '@nestjs/websockets'; @WebSocketGateway() export class ChatGateway { @SubscribeMessage('message') handleMessage(@MessageBody() msg: string): string { console.log('收到消息:', msg); return '服务器回复:' + msg; } }
十八、任务调度(CronJob)
npm install @nestjs/schedule
app.module.ts
import { ScheduleModule } from '@nestjs/schedule'; @Module({ imports: [ScheduleModule.forRoot()], }) export class AppModule {}
task.service.ts
import { Injectable } from '@nestjs/common'; import { Cron } from '@nestjs/schedule'; @Injectable() export class TaskService { @Cron('*/5 * * * * *') handleTask() { console.log('每5秒执行一次任务'); } }
参考案例:www.yllbn.cn
十九、JWT 登录认证
npm install @nestjs/jwt passport-jwt @nestjs/passport
登录后生成 Token:
import { JwtService } from '@nestjs/jwt'; constructor(private jwt: JwtService) {} login(user: any) { const payload = { username: user.name }; return { token: this.jwt.sign(payload) }; }
守卫验证:
@UseGuards(AuthGuard('jwt')) @Get('profile') getProfile() { return { user: '张三' }; }
二十、完整实战项目:留言板后端 API
message.entity.ts
import { Entity, Column, PrimaryGeneratedColumn } from 'typeorm'; @Entity() export class Message { @PrimaryGeneratedColumn() id: number; @Column() author: string; @Column() content: string; }
message.service.ts
@Injectable() export class MessageService { constructor(@InjectRepository(Message) private repo: Repository<Message>) {} create(msg: Partial<Message>) { return this.repo.save(msg); } findAll() { return this.repo.find(); } }
message.controller.ts
@Controller('message') export class MessageController { constructor(private msgService: MessageService) {} @Get() findAll() { return this.msgService.findAll(); } @Post() create(@Body() body: any) { return this.msgService.create(body); } }
运行项目后:
-
POST /message添加留言 -
GET /message获取留言
火山引擎开发者社区是火山引擎打造的AI技术生态平台,聚焦Agent与大模型开发,提供豆包系列模型(图像/视频/视觉)、智能分析与会话工具,并配套评测集、动手实验室及行业案例库。社区通过技术沙龙、挑战赛等活动促进开发者成长,新用户可领50万Tokens权益,助力构建智能应用。
更多推荐
所有评论(0)