1、node版本 >12
2、利用脚手架安装
$ npm i -g @nestjs/cli
$ nest new project-name
3、src目录核心文件
- app.controller.ts带有单个路由的基本控制器示例。
- app.controller.spec.ts对于基本控制器的单元测试样例
- app.module.ts应用程序的根模块。
- app.service.ts带有单个方法的基本服务
- main.ts应用程序入口文件。它使用
NestFactory用来创建 Nest 应用实例。
//main.js代码示例
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
async function bootstrap() {
const app = await NestFactory.create(AppModule);
await app.listen(3000);
}
bootstrap();
启动
pnpm run start:dev
浏览器访问localhost:3000,会看到你的接待小姐姐:hello world
简单介绍
当浏览器访问localhost:3000时,会自动匹配路由,controller是路由文件。
程序监听3000端口,当有请求进来时判断是get还是post或者其它,把路由参数分解一一去匹配,修饰器里的路由被匹配上,就会执行相应的方法
import { Controller, Get } from '@nestjs/common';
import { AppService } from './app.service';
@Controller()
export class AppController {
constructor(private readonly appService: AppService) {}
@Get()
getHello(): string {
return this.appService.getHello();
}
}
@Get()是修饰器的写法,不熟悉的同学可以去看看相关文档。在这里表示 1、get请求。2、路径为空
this.appService.getHello()调用service中的方法 并返回,最终呈现到页面上