当前位置: 首页 > 后端技术 > Node.js

Nest.js入门小例子

时间:2023-04-03 10:18:39 Node.js

Nest.js入门小例子不能满足我们的需求,而对于新手来说,有一个完整的入门例子也是至关重要的。示例目录结构如下:代码编写工具采用VSCode。目录功能具体说明:first-nestjs-app项目根目录node_modulesnode.js模块安装目录。cli工具不会生成此目录。需要自己安装srccli工具生成的源码目录test。test目录的src目录下的test目录是我自定义的demo代码目录。具体代码说明:test.controller.tsimport{Get,Controller}from'@nestjs/common';从'./test.service'导入{TestService};//引用服务文件@Controller('test')///test/路径exportclassTestController{constructor(privatereadonlytestService:TestService){}@Get()///test/路径firstTest函数名可以任意firstTest():string{returnthis.testService.test();}@Get(':id')///test/1和其他路径findOneTest():string{returnthis.testService.findOneTest();}}//控制器只是简单的路由转发,具体逻辑由服务文件处理决定。test.service.tsimport{Injectable}from'@nestjs/common';@Injectable()exportclassTestService{test():string{//测试名称和test.controller.ts调用应该对应return'testtesttest!';//具体逻辑处理在这里}findOneTest():string{return'findOneTest!';}}test.module.tsimport{Module}from'@nestjs/common';import{TestController}from'./test.controller';import{TestService}from'./test.service';//在Module配置文件中配置对应的controller和service@Module({imports:[],controllers:[TestController],providers:[TestService]})exportclassTestModule{}app.module.ts//最后需要在app.module.ts的配置中加入TestModuleimport{Module}from'@nestjs/common';import{AppController}from'./app.controller';从'./app.service'导入{AppService};从'./test/test.module'导入{TestModule};//引入文件@Module({imports:[TestModule],//在这里添加controllers:[AppController],providers:[AppService]})exportclassAppModule{}最后,先安装所有依赖,npminstall或者cnpminstall,然后在根目录下执行npmstartrun。然后在浏览器中访问http://localhost:3000/test/和http://localhost:3000/test/1输出不同的结果PS:这个例子还需要Node.js和Nest.js的版本(5.0orabove),具体请参考官方文档。Nest.js有中文文档,但有时网站无法访问。不过github上有中文翻译托管。GitHub上还提供了此示例的完整代码。