1、安装 Node 环境. 下载安装后,Node >= 10.13.0 即可, 可通过命令行检查
node -v
2.安装 NestJS cli
npm i -g @nestjs/cli
- // step1
- nest new nest-test
-
- // step2 Which package manager would you
- 选择: npm
- src
- |- app.controller.spec.ts // controller 的测试文件
- |- app.controller.ts // controller,路由和预处理
- |- app.module.ts // module,为模块注册用
- |- app.service.ts // service 真正的逻辑
- |- main.ts // 程序入口

module 的作用是在程序运行时给模块处理依赖。好处是所有模块的依赖都可以在 module 中清晰明了的知道引用还是被引用

controller 的作用是处理请求,所有的请求会先到 controller,再经 controller 调用其他模块业务逻辑
是真正处理业务逻辑的地方,所有的业务逻辑都会在这里处理。它可经过 module 引用其他模块的service,也可经过 module 暴露出去。
- // step1: 进入目录
- cd nest-test
-
- // step2: 安装依赖或更新依赖
- npm install
-
- // step3: 运行程序
- npm run start
访问url
- // ✅
- 访问: http://localhost:3000/
- // => Hello World!
NestJS cli 支持用命令行形式来创建,这样就不需要做重复的创建文件的动作了。
- nest g controller students
- nest g service students
- nest g module students
再命令行分别执行以上三条命令,src/ 目录变成了如下样子
- src
- |- app.controller.spec.ts
- |- app.controller.ts
- |- app.module.ts
- |- app.service.ts
- |- main.ts
- |- students/
- |- students.controller.spec.ts
- |- students.controller.ts
- |- students.module.ts
- |- students.service.spec.ts
- |- students.service.ts
- // students.service.ts
- import { Injectable } from '@nestjs/common';
-
- @Injectable()
- export class StudentsService {
- ImStudent() {
- return 'Im student';
- }
- }
- // students.controller.ts
- import { Controller, Get } from '@nestjs/common';
- import { StudentsService } from './students.service';
-
- @Controller('students')
- export class StudentsController {
- constructor(private readonly studentsService: StudentsService) {}
-
- @Get('who-are-you')
- whoAreYou() {
- return this.studentsService.ImStudent();
- }
- }
重启服务, 加上 dev 就能监听文件修改了。
npm run start:dev
最后访问url
- // ✅
- http://localhost:3000/students/who-are-you
- // => Im student