NestJS 框架¶
一句话概述:NestJS 是 Node.js 的企业级 TypeScript 框架,借鉴 Angular 的架构思想(模块、依赖注入、装饰器),提供开箱即用的微服务、GraphQL、WebSocket 支持。
核心知识点¶
| 概念 | 白话解释 |
|---|---|
| Module | 模块 = 功能的组织单元,每个功能一个模块 |
| Controller | 控制器 = 处理 HTTP 请求,定义路由 |
| Service/Provider | 服务 = 业务逻辑层,被注入到控制器中 |
| Dependency Injection | 依赖注入 = NestJS 自动管理对象的创建和传递 |
| Decorator | 装饰器 = @Controller、@Get 等注解 |
| Pipe | 管道 = 数据验证和转换 |
| Guard | 守卫 = 路由级别的权限控制 |
| Interceptor | 拦截器 = 请求/响应的通用处理逻辑 |
安装配置¶
npm i -g @nestjs/cli # 安装 NestJS CLI
nest new my-project # 创建新项目(自动生成完整结构)
cd my-project && npm run start:dev # 启动开发模式
基本使用¶
Controller + Service¶
// users.controller.ts
import { Controller, Get, Post, Body, Param, Query } from '@nestjs/common';
import { UsersService } from './users.service';
import { CreateUserDto } from './dto/create-user.dto';
@Controller('users') // 路由前缀 /users
export class UsersController {
constructor(private readonly usersService: UsersService) {} // 自动注入
@Get() // GET /users
findAll(@Query('page') page: number = 1) {
return this.usersService.findAll(page);
}
@Get(':id') // GET /users/:id
findOne(@Param('id') id: string) {
return this.usersService.findOne(id);
}
@Post() // POST /users
create(@Body() createUserDto: CreateUserDto) {
return this.usersService.create(createUserDto);
}
}
// users.service.ts
import { Injectable, NotFoundException } from '@nestjs/common';
@Injectable() // 标记为可注入的服务
export class UsersService {
private users = [];
findAll(page: number) {
return { data: this.users, page };
}
findOne(id: string) {
const user = this.users.find(u => u.id === id);
if (!user) throw new NotFoundException('用户不存在');
return user;
}
create(dto: any) {
const user = { id: Date.now().toString(), ...dto };
this.users.push(user);
return user;
}
}
// dto/create-user.dto.ts — 数据验证
import { IsString, IsEmail, MinLength } from 'class-validator';
export class CreateUserDto {
@IsString()
@MinLength(3)
name: string;
@IsEmail()
email: string;
@IsString()
@MinLength(8)
password: string;
}
// users.module.ts — 模块
import { Module } from '@nestjs/common';
import { UsersController } from './users.controller';
import { UsersService } from './users.service';
@Module({
controllers: [UsersController],
providers: [UsersService],
exports: [UsersService], // 导出供其他模块使用
})
export class UsersModule {}
高级用法¶
Guard(权限守卫)¶
import { Injectable, CanActivate, ExecutionContext } from '@nestjs/common';
@Injectable()
export class AuthGuard implements CanActivate {
canActivate(context: ExecutionContext): boolean {
const request = context.switchToHttp().getRequest();
return !!request.headers.authorization; // 有 Token 才放行
}
}
// 使用
@UseGuards(AuthGuard)
@Get('profile')
getProfile() { ... }
Interceptor(拦截器)¶
@Injectable()
export class TransformInterceptor implements NestInterceptor {
intercept(context: ExecutionContext, next: CallHandler) {
return next.handle().pipe(
map(data => ({ success: true, data, timestamp: new Date() }))
); // 统一包装响应格式
}
}
常见报错¶
| 报错信息 | 原因 | 解决方法 |
|---|---|---|
Nest can't resolve dependencies | 依赖注入失败 | 检查 Module 的 imports/providers |
Cannot GET /xxx | 路由不存在 | 检查 Controller 路径和 Module 注册 |
ValidationPipe error | DTO 验证失败 | 检查请求数据格式 |
速查表¶
# === CLI 命令 ===
nest new <project> # 创建项目
nest g module <name> # 生成模块
nest g controller <name> # 生成控制器
nest g service <name> # 生成服务
nest g resource <name> # 生成完整 CRUD 资源
npm run start:dev # 开发模式
npm run build && npm run start:prod # 生产模式
# === 装饰器 ===
@Controller('path') @Get() @Post() @Put() @Delete()
@Body() @Param() @Query() @Headers()
@UseGuards() @UseInterceptors() @UsePipes()
@Injectable() @Module() @Global()
参考:NestJS 文档 | 更新于 2026 年