Nestjs框架安裝與啓動

Nest是構建高效可擴展的 Node.js Web 應用程序的框架。 默認使用JavaScript的超集TypeScript進行開發。

環境準備

查看node和npm版本:

$ node --version
v10.11.0
$ npm --version
6.5.0

安裝@nestjs/cli

使用npm全局安裝@nestjs/cli:

$ npm i -g @nestjs/cli
/usr/local/bin/nest -> /usr/local/lib/node_modules/@nestjs/cli/bin/nest.js
+ @nestjs/[email protected]
added 11 packages from 6 contributors, 
removed 27 packages and updated 12 packages in 10.322s

使用nest --version命令查看nest當前版本:

$ nest --version
5.7.1

使用nest new命令創建一個名爲nest-app的項目:

$ nest new nest-app    

⚡️  Creating your Nest project...
🙌  We have to collect additional information:

? description: TEST nest-app
? version: 0.0.1
? author: wangyt

💥  Thank you for your time!

CREATE /nest-app/.prettierrc (51 bytes)
CREATE /nest-app/README.md (3441 bytes)
CREATE /nest-app/nodemon-debug.json (163 bytes)
CREATE /nest-app/nodemon.json (132 bytes)
CREATE /nest-app/package.json (1653 bytes)
CREATE /nest-app/tsconfig.build.json (109 bytes)
CREATE /nest-app/tsconfig.json (390 bytes)
CREATE /nest-app/tsconfig.spec.json (137 bytes)
CREATE /nest-app/tslint.json (426 bytes)
CREATE /nest-app/src/app.controller.spec.ts (592 bytes)
CREATE /nest-app/src/app.controller.ts (274 bytes)
CREATE /nest-app/src/app.module.ts (249 bytes)
CREATE /nest-app/src/app.service.ts (142 bytes)
CREATE /nest-app/src/main.ts (208 bytes)
CREATE /nest-app/test/app.e2e-spec.ts (599 bytes)
CREATE /nest-app/test/jest-e2e.json (183 bytes)
CREATE /nest-app/nest-cli.json (84 bytes)
? Which package manager would you ❤️  to use? npm
✔ Installation in progress... ☕️
🚀  Successfully created project nest-app
👉  Get started with the following commands:
  $ cd nest-app
  $ npm run start
          Thanks for installing Nest 🙏
 Please consider donating to our open collective
        to help us maintain this package.                       
🍷  Donate: https://opencollective.com/nest

啓動項目

進入項目,並啓動項目

$ cd nest-app 
$ npm run start

> [email protected] start /Users/wangtom/development/nest-app
> ts-node -r tsconfig-paths/register src/main.ts
[Nest]6315 - 2018-12-18 09:52:48[NestFactory]Starting Nest application...
[Nest]6315 - 2018-12-18 09:52:48[InstanceLoader]AppModule dependencies initialized +9ms
[Nest]6315 - 2018-12-18 09:52:48[RoutesResolver]AppController {/}: +34ms
[Nest]6315 - 2018-12-18 09:52:48[RouterExplorer]Mapped {/, GET} route +2ms
[Nest]6315 - 2018-12-18 09:52:48[NestApplication]Nest application successfully started +1ms

打開瀏覽器,訪問http://localhost:3000/就可以看到Hello World!頁面輸出了。

項目結構

可以使用tree命令查看nest-app的目錄結構:

nest-app
├── README.md
├── nest-cli.json
├── node_modules/
├── nodemon-debug.json
├── nodemon.json
├── package-lock.json
├── package.json
├── src
│   ├── app.controller.spec.ts
│   ├── app.controller.ts
│   ├── app.module.ts
│   ├── app.service.ts
│   └── main.ts
├── test
│   ├── app.e2e-spec.ts
│   └── jest-e2e.json
├── tsconfig.build.json
├── tsconfig.json
├── tsconfig.spec.json
└── tslint.json

可以看到,和Angular的項目結構很像。

src/main.ts是項目的入口文件, 定義了一個異步方法(bootstrap)來啓動應用,默認監聽端口3000:

// main.ts
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';

async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  await app.listen(3000);
}
bootstrap();

控制器: app.controller.ts

// app.controller.ts
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();
  }
  // 自定義 getVersion 方法: 
  @Get('/version')
  getVersion(): Object {
    return this.appService.getVersion();
  }
}

控制器文件src/app.controller.ts中定義了一個getHello方法,使用@Get()進行路由註解。
getHello方法,調用了appService中的getHello方法,返回了 Hello World!;

// app.service.ts
import { Injectable } from '@nestjs/common';

@Injectable()
export class AppService {
  getHello(): string {
    return 'Hello World!';
  }
  // 自定義:獲取版本
  getVersion(): Object {
    return {
      code: 200, 
      msg: "",
      data: {
        version:"0.0.1"
      }, 
    }
  }
}

自定義一個返回當前版本的接口,獲取當前應用的版本:

在控制器app.controller.ts新增getVersion方法,使用@Get('/version')路由註解,表示訪問’/version’會調用次方法。

在服務類app.service.ts中新增getVersion方法,用來返回內容,返回格式爲Object

使用Control+C結束終端,這次我們使用npm run start:dev啓動(項目文件有修復會自動重啓):

$ npm run start:dev  

> [email protected] start:dev /Users/wangtom/development/nest-app
> nodemon
[nodemon] 1.18.9
[nodemon] to restart at any time, enter `rs`
[nodemon] watching: /Users/wangtom/development/nest-app/src/**/*
[nodemon] starting `ts-node -r tsconfig-paths/register src/main.ts`
 ... 

訪問http://localhost:3000/version, 輸出json字符串內容:

{"code":200,"msg":"","data":{"version":"0.0.1"}}

參考鏈接

https://docs.nestjs.com/first-steps

感謝閱讀,如有問題請留言。

[END]

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章