-
Nest
是一個漸進式的Node框架,可以在TypeScript
和JavaScript(ES6例书、ES7昧捷、ES8)
之上構建高效、可伸縮的企業(yè)級服務端應用程序堤框; -
Nest
基于TypeScritp
編寫域滥、并結合使用OOP(面向對象編程)
、FP(函數式編程)
和ERP(函數式響應編程)
的相關理念蜈抓; -
Nest
的設計靈感很多來自于Angular
启绰,而Angular
的很多模式又來自于Java
的Spring
框架,諸如AOP(面向切片編程)沟使、依賴注入委可、控制反轉
等等,所以Nest
是Node
版的Spring
框架格带! -
Nest
底層HTTP
平臺默認基于Express
實現(xiàn)的撤缴,所以無需擔心第三方庫的缺失刹枉;技術上講,Nest
可以在創(chuàng)建適配器后使用任何Node Http
框架屈呕,但它提供了兩個開箱即用的HTTP
平臺:Express微宝、Fastify
; -
Nest
的核心思想:提供一個層與層之間的耦合度極小虎眨、抽象化極高的架構體系蟋软。
環(huán)境搭建
- 腳手架:
npm i -g @nestjs/cli yarn global add @nestjs/di
- 創(chuàng)建項目:
nest new project-name
- 運行項目:
npm run start
- 熱重載運行:
npm run start:dev
nest結構.png
控制器
- 控制器層負責處理用戶的請求,并做出響應嗽桩;
Client ---> Controller-1岳守、Controller-2、Controller-3
- 創(chuàng)建控制器:
nest g controller xxx
- 在
src
目錄中生成xxx
目錄碌冶,其中包含xxx.controller.ts
- 控制器是一個裝飾了
Controller
的類湿痢,xxx
生成對應的@Controller('xxx')
- 同時在根模塊
app.module.ts
中,引入了此控制器:controllers:[AppController, XxxController]
- 在
-
@Get
裝飾器處理Get
請求@Controller('xxx') export class XxxController { @Get() // http://localhost:3000/xxx index() { return 'hello xxx' } @Get('add') // http://localhost:3000/xxx/add add() { return 'hello xxx add' } }
- 處理
Get
傳參:@Query
@Get('add') // http://localhost:3000/xxx/add?id=123&name=Jack add(@Query() query) { // { id: 123, name: Jack } return 'hello xxx add' } @Get('add') add(@Query('id') id) { // 指定只獲取某一個參數 return id // 123 }
-
@Request
也可以處理Get參數扑庞,類似于Express
平臺的Request
譬重,包含有請求的完整信息。
@Get('add') // http://localhost:3000/xxx/add?id=123&name=Jack add(@Request() req) { return req.query // { id: 123, name: Jack } }
- 處理
-
@Post
裝飾器處理Post
請求@Post('create') create() { return 'hello xxx create' }
-
@Body
處理Post參數
@Post('create') create(@Body() body) { return 'hello xxx create' }
-
@Body
也可以指定只獲取某一個參數:@Body('key')
-
-
@Param
處理動態(tài)路由的參數@Get(':id') // http://localhost:3000/xxx/111 show(@Param() param) { console.log(param) // { id: 111 } return 'hello xxx' } @Get(':id') show(@Param('id') id) { // 指定只獲取 id return id // 111 }
- 模糊匹配罐氨,如
*
表示匹配n(n>=0)
個字符@Get('a*a') // http://localhost:3000/xxx/adda add() { return 'hello xxx add' }
-
@Headers(name?: string)
:獲取請求頭臀规;@Redirect
:重定向; -
@Response()
:響應對象的裝飾器栅隐∷遥控制器方法不能再通過return
響應數據,而是使用Response
對象自身的方法租悄。@Get() admin(@Response() res) { res.redirect('/user'); //重定向 } @Get('add') add(@Response() res) { res.send({ msg: 'success' }); //響應數據 }
配置靜態(tài)資源
- 靜態(tài)資源配置依賴所使用的平臺谨究,以
Express
平臺為例 -
main.ts
import { NestExpressApplication } from '@nestjs/platform-express'; async function bootstrap() { // 通過泛型指定使用的平臺Express const app = await NestFactory.create<NestExpressApplication>(AppModule); //配置靜態(tài)資源的目錄:根目錄/public app.useStaticAssets('public'); await app.listen(3000); }
-
public
目錄中的靜態(tài)資源可以直接訪問:http://localhost:3000/logo.png
- 還可以配置虛擬目錄
app.useStaticAssets('public', { prefix: '/static/' }); //訪問:http://localhost:3000/static/logo.png
配置模板引擎
- 以
ejs
為例:npm i ejs --save
-
main.ts
:配置視圖文件的目錄,指定使用的模板引擎恰矩;app.setBaseViewsDir('views'); // 根目錄/views app.setViewEngine('ejs');
- 創(chuàng)建視圖
views/admin/index.ejs
<h2>姓名:<%= name%></h2> <h2>年齡:<%= age%></h2>
- 在控制器中渲染并響應視圖
@Get() @Render('admin/index') admin() { return { name: 'Mack', age: 20 } //向模板中傳遞數據 }
服務
-
Nestjs
中的服務可以是service
记盒,也可以是provider
,可以通過constructor
注入依賴關系外傅; - 服務本質上就是通過
@Injectable()
裝飾的類纪吮,在Nestjs
中,服務相當于MVC的Model
萎胰; - 創(chuàng)建服務
nest g service xxx
- 生成
xxx/xxx.service.ts
import {Injectable} from '@nestjs/common' @Injectable() export class XxxService { find() { return {name: 'Jack', age: 20}; } }
- 根模塊
app.module.ts
中碾盟,自動引入服務
providers: [AppService, XxxService]
- 在需要使用的地方注入服務對象
nest g controller xxx //創(chuàng)建控制器 @Controller('xxx') export class XxxController { //依賴注入 constructor(private service: XxxService) { } @Get() index() { return this.service.find(); } }
- 生成