Skip to content

NestJS

资料

NestJS 英文官网

NestJS 中文网

!!!推荐视频 - 小满NestJS

NestJS 作者及联系方式

NestJS 内置 Express 及 Fastify

前置知识

依赖注入(DI) 及 控制翻转(IOC)

TS 装饰器

Nest Cli

安装

# 安装脚手架
npm i -g @nest/cli

# 新建工程
nest new 工程名
1
2
3
4
5

文件作用


app.controller.ts 带有单个路由的基本控制器示例(处理http请求及调用service层方法)。
app.controller.spec.ts 对于基本控制器的单元测试样例 
app.module.ts 应用程序的根模块(处理其他类的引用与共享)。
app.service.ts 带有单个方法的基本服务(封装通用业务逻辑、数据库及数据交互,其他三方请求)。 

main.ts 应用程序入口文件。它使用 NestFactory 用来创建 Nest 应用实例。

1
2
3
4
5
6
7
8

常用Cli命令

nest --help # 查看nestjs所有命令

# 单个文件生成器(生成后 nest 会自动引入)
nest g co demo # 生成名为 demo 的 controller
nest g mo demo # 生成名为 demo 的 module
nest g s demo # 生成名为 demo 的 service

# 一次性生成 CRUD 所需文件(一般选择 Restfull API 及 yes)
nest g resource user # 生成名为 user 的一套 CRUD 文件

# 生成中间件 logger
nest g mi logger
1
2
3
4
5
6
7
8
9
10
11
12

常用包

# session
yarn add express-session
# session ts 声明
yarn add @types/express-session


# 图片验证码
yarn add svg-captcha

# axios 携带 cookie 配置
axios.defaults.withCredentials = true

# 添加 swagger 文档
yarn add @nestjs/swagger swagger-ui-express class-validator

# 跨域
yarn add cors
yarn add @types/cors
# 前端请求
fetch('http://localhost:5005/list').then(res => res.json()).then(res => { console.log(res) })

# 上传需求的包
yarn add multer
yarn add @types/multer

# 下载用到的包
yarn add compressing

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28

Released under the MIT License. Thanks to WebStorm software support.