NestJS核心概念之Middleware中間件創(chuàng)建使用示例
前言
用過express
與koa
的同學(xué),對中間件這個概念應(yīng)該非常熟悉了,中間件可以拿到Request
、Response
對象和next
函數(shù).
一般來講中間件有以下作用:
- 執(zhí)行任何代碼
- 對請求與響應(yīng)攔截并改造
- 結(jié)束
request-response
周期 - 通過
next()
調(diào)用下一個中間件 - 如果當(dāng)前中間件沒有結(jié)束當(dāng)前
request-response
周期,必須調(diào)用next()
函數(shù),否則請求會處于掛起狀態(tài),阻塞整個應(yīng)用
中間件一般有兩種:類中間件、函數(shù)中間件
類中間件
創(chuàng)建類中間件
使用@Injectable()
裝飾器,并且需要實現(xiàn)NestMiddleware
接口(use
方法)
// Logger.middleware.ts import { Injectable, NestMiddleware } from "@nestjs/common"; import { Request, Response } from "express"; @Injectable() export class LoggerMiddleware implements NestMiddleware { use(req: Request, res: Response, next: () => void) { console.log('logger middleware', `url: ${req.url}`); next(); } }
使用類中間件
類中間創(chuàng)建完之后,需要在模塊中進行掛載,但@Module
裝飾器并沒有中間件的相關(guān)配置,我們需要讓module
類實現(xiàn)NestModule
接口,實現(xiàn)里面configure方法來進行掛載
// user.module.ts import { Module, NestModule } from '@nestjs/common'; import { UserService } from './user.service'; import { UserController } from './user.controller'; import { LoggerMiddleware } from '../middleware/Logger.middleware'; @Module({ controllers: [UserController], providers: [UserService] }) export class UserModule implements NestModule { configure(consumer) { consumer .apply(LoggerMiddleware) .forRoutes(UserController); } }
apply
方法表示掛載的是哪個中間件forRoutes
方法表示對哪個請求路徑起作用,這種方式與app.use(path, middleware)
作用是一樣,只針對部分路徑起作用- 當(dāng)給
forRoutes
方法傳遞的是一個controller
控制器時,那么該中間件則對整個控制器下的路徑生效
比如這里傳遞的是UserController
控制器,那么針對該控制器下的路徑都會生效
forRootes
方法還能做更詳細的配置,比如可以針對特定的請求方法、請求路徑可以使用正則匹配(需要注意的是使用fastify
驅(qū)動不能使用)
export class UserModule implements NestModule { configure(consumer) { consumer .apply(LoggerMiddleware) .forRoutes({ path: 'user', method: RequestMethod.GET}); } }
apply
可以同時掛載多個中間件
export class UserModule implements NestModule { configure(consumer) { consumer .apply(LoggerMiddleware, aaaMiddleware, ...) .forRoutes({ path: 'user', method: RequestMethod.GET}); } }
forRoutes
可以使用單個string
路徑,多個string
路徑,RouteInfo
對象,單個Controller
,多個Controller
export class AppModule implements NestModule { configure(consumer) { consumer .apply(LoggerMiddleware, NjMiddleware, ...) .forRoutes(UserController, NjController, ...); } }
exclude
可以用來排除不使用中間件的路徑
export class UserModule implements NestModule { configure(consumer) { consumer .apply(LoggerMiddleware) .exclude({ path: '/user/a', method: RequestMethod.GET}) .forRoutes(UserController); } }
需要注意的是forRoutes
需要最后調(diào)用
函數(shù)中間件
這種方式較為簡單,使用起來與類中間件一致
創(chuàng)建函數(shù)中間件
export function LoggerMiddleware(req: Request, res: Response, next: () => void) { console.log('logger middleware', `url: ${req.url}`); next(); }
使用函數(shù)中間件
export class UserModule implements NestModule { configure(consumer) { consumer .apply(LoggerMiddleware) .exclude({ path: '/user/a', method: RequestMethod.GET}) .forRoutes(UserController); } }
全局中間件
可以直接在入口文件main.ts
中使用app.use
來掛載中間件,這樣掛載的中間件將全局生效
app.use(LoggerMiddleware) // 日志中間件
中間件其實可以用來實現(xiàn)很多功能,比如:日志系統(tǒng)、cors跨域處理、圖片防盜等...
對圖片防盜感興趣的可以看我這篇文章:你不知道的 HTTP Referer
以上就是NestJS核心概念之Middleware中間件創(chuàng)建使用示例的詳細內(nèi)容,更多關(guān)于NestJS Middleware中間件的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
Node使用Puppeteer監(jiān)聽并打印網(wǎng)頁的接口請求
Puppeteer 是一個 Node 庫,它提供了高級的 API 來通過 DevTools 協(xié)議控制 Chrome 或 Chromium,本文我們就來看看如何使用Puppeteer監(jiān)聽并打印網(wǎng)頁的接口請求吧2025-04-04Node解決簡單重復(fù)問題系列之Excel內(nèi)容的獲取
這篇文章主要給大家介紹了關(guān)于利用Node解決簡單重復(fù)問題系列之Excel內(nèi)容獲取的相關(guān)資料,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)吧。2018-01-01Node.js實現(xiàn)前端后端數(shù)據(jù)傳輸加密解密
這篇文章主要介紹了Node.js實現(xiàn)前端后端數(shù)據(jù)傳輸加密解密,文章圍繞主題展開詳細的內(nèi)容介紹,具有一定的參考價值,需要的小伙伴可以參考一下2022-08-08輕松創(chuàng)建nodejs服務(wù)器(7):阻塞操作的實現(xiàn)
這篇文章主要介紹了輕松創(chuàng)建nodejs服務(wù)器(7):阻塞操作的實現(xiàn),本文先是組出了代碼,然后對代碼一一分析,需要的朋友可以參考下2014-12-12使用nodejs?+?koa?+?typescript?集成和自動重啟的問題
這篇文章主要介紹了nodejs?+?koa?+?typescript?集成和自動重啟,本文給大家介紹的非常詳細,對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2021-12-12