NestJS + TypeORM + PostgreSQL 从零搭建后端 API(保姆级教程)
从零开始搭建 NestJS 后端项目,集成 TypeORM 操作 PostgreSQL 数据库,实现 CRUD 接口、JWT 鉴权、文件上传等常用功能。
为什么选 NestJS
NestJS 是目前 Node.js 生态里架构最完善的后端框架,借鉴了 Angular 的模块化思想,天然支持 TypeScript,有完整的 IoC/DI 容器。
项目初始化
npm install -g @nestjs/cli
nest new my-api
cd my-api
npm install @nestjs/typeorm typeorm pg
配置 PostgreSQL 连接
TypeOrmModule.forRoot({
type: 'postgres',
url: process.env.DATABASE_URL,
entities: [__dirname + '/**/*.entity{.ts,.js}'],
synchronize: false,
})
定义 Entity
@Entity('articles')
export class Article {
@PrimaryGeneratedColumn() id: number;
@Column({ unique: true }) slug: string;
@Column() title: string;
@Column({ type: 'text' }) content: string;
@CreateDateColumn() createdAt: Date;
}
JWT 鉴权
npm install @nestjs/jwt @nestjs/passport passport-jwt
实现 JwtStrategy,配合 @UseGuards(AuthGuard('jwt')) 装饰器保护路由。