nest小結

一 :nest/cli? 常見命令

1 生成中間件。 nest g middle name (生成中間件)

2 生成攔截器。? nest g interceptor name xxx

3?生成守衛。? nest g gu name xxx

二: 如何在項目中如何應用多個中間件?

import { Injectable, NestMiddleware } from '@nestjs/common';@Injectable()
export class Mid1Middleware implements NestMiddleware {use(req: any, res: any, next: () => void) {console.log("middle1-----")next();}
}----------------------------------------
import { Injectable, NestMiddleware } from '@nestjs/common';@Injectable()
export class Mid2Middleware implements NestMiddleware {use(req: any, res: any, next: () => void) {console.log("middle2-----")next();}
}

step2:改寫app.module.ts

export class AppModule implements NestModule{configure(consumer: MiddlewareConsumer) {consumer.apply(Mid1Middleware,Mid2Middleware).forRoutes("*")// consumer.apply(Mid2Middleware).forRoutes("*")}}

apply方法中傳入多個中間件函數名稱即可

三:如何實現http的攔截器?

step1 :?nest g interceptor interceptor/reqest? ? |? ? nest g interceptor interceptor/response

該命令將生成目錄interceptor,且包含reqest和response兩個函數

setp2 :?

request
-----------------------------------import { CallHandler, ExecutionContext, Injectable, NestInterceptor } from '@nestjs/common';
import { Observable } from 'rxjs';@Injectable()
export class ReqestInterceptor implements NestInterceptor {intercept(context: ExecutionContext, next: CallHandler): Observable<any> {console.log("before request-----")return next.handle();}
}response
-----------------------------------
import { CallHandler, ExecutionContext, Injectable, NestInterceptor } from '@nestjs/common';
import { Observable, map } from 'rxjs';@Injectable()
export class ResponseInterceptor implements NestInterceptor {intercept(context: ExecutionContext, next: CallHandler): Observable<any> {console.log("response request----")return next.handle().pipe(map(data=>({data,status:200,message:'ok'})))}
}//在返回值中我們定義了攔截以后的數據格式

step3 :應用攔截器

import { Controller, Get, UseInterceptors } from '@nestjs/common';
import { AppService } from './app.service';
import {ResponseInterceptor} from "./interceptor/response/response.interceptor"
@Controller()
export class AppController {constructor(private readonly appService: AppService) {}@Get()getHello(): string {return this.appService.getHello();}@Get('list')@UseInterceptors(ResponseInterceptor)   //這里是關鍵,UseInterceptors裝飾器可以對制定的路由進行攔截getList(){let arr=[{id:1,name:"aaaa"},{id:2,name:"bbbbb"},{id:3,name:"ccccc"},{id:4,name:"dddddd"},]return arr //我們只需要正常返回數據即可,攔截器會自動把最后的數據格式進行轉換}
}

提示:這里我們是針對某些具體的請求做了攔截處理,包括返回值格式化,如果要對全局所有接口都作統一的處理,這時候我們需要做如下更改

app.module.ts中

import { APP_INTERCEPTOR } from '@nestjs/core';
import { ResponseInterceptor } from './interceptor/response/response.interceptor';
import { ReqestInterceptor } from './interceptor/reqest/reqest.interceptor';
@Module({imports: [],controllers: [AppController],providers: [AppService,{provide:APP_INTERCEPTOR,useClass:ReqestInterceptor},{provide:APP_INTERCEPTOR,useClass:ResponseInterceptor}],
})
export class AppModule implements NestModule{configure(consumer: MiddlewareConsumer) {consumer.apply(Mid1Middleware,Mid2Middleware).forRoutes("*")// consumer.apply(Mid2Middleware).forRoutes("*")}}

providers選項中我們引入了APP_INTERCEPTOR選項。同時應用RequestInterceptor和ResponseInterceptor,這樣就能實現全局的路由攔截

四:nest如何守衛?(以判斷請求中是否有token為例)

step1: nest g gu AuthGurd

step2:?

import { CanActivate, ExecutionContext, Injectable } from '@nestjs/common';
import { Observable } from 'rxjs';@Injectable()
export class AuthgurdGuard implements CanActivate {canActivate(context: ExecutionContext,): boolean | Promise<boolean> | Observable<boolean> {const request =context.switchToHttp().getRequest()const token=request.headers['authorization']if(token && token ==='abc123'){return true}return false;}
}

step3:在controller中對請求作守衛

import { Controller, Get, UseGuards, UseInterceptors } from '@nestjs/common';
import { AppService } from './app.service';
import {ResponseInterceptor} from "./interceptor/response/response.interceptor"
import { AuthgurdGuard } from './authgurd/authgurd.guard';
@Controller()export class AppController {constructor(private readonly appService: AppService) {}@Get()getHello(): string {return this.appService.getHello();}@Get('list')@UseGuards(AuthgurdGuard)// @UseInterceptors(ResponseInterceptor)getList(){let arr=[{id:1,name:"aaaa"},{id:2,name:"bbbbb"},{id:3,name:"ccccc"},{id:4,name:"dddddd"},]return arr}
}

以上我們以list接口為例,請求http://localhost:3000/list如果header中沒有token則會報錯,而其他接口則不受影響。

同樣,如果想讓AuthGuard全局生效。則可以在app.module.ts中采用如下方式:

import { APP_GUARD, APP_INTERCEPTOR } from '@nestjs/core';
import { AuthgurdGuard } from './authgurd/authgurd.guard';@Module({imports: [],controllers: [AppController],providers: [AppService,{provide:APP_GUARD, //這里是核心useClass: AuthGuard,},],
})

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/697656.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/697656.shtml
英文地址,請注明出處:http://en.pswp.cn/news/697656.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

Python學習筆記——認識Python軟件包

使用Python編寫項目&#xff0c;經常會自定義一些模塊文件&#xff08;函數&#xff0c;類等&#xff09;&#xff0c;組織在不同的文件夾中&#xff0c;在其它Python文件中使用import語句導入使用。Python軟件包和普通的文件夾不同之處在于有一個特定文件“__init__.py”。當導…

vue中的this.$emit方法:用于子組件中觸發父組件方法并傳值

vue中的this.$emit方法 使用一&#xff1a;$emit使用二&#xff1a;$emit update 和 .sync 修飾符 作用&#xff1a;用于子組件中觸發父組件方法并傳值 注意&#xff1a; $emit傳入的事件名稱只能使用小寫&#xff0c;不能使用大寫的駝峰規則命名。 使用一&#xff1a;$emit …

【正點原子STM32連載】 第五十五章 FreeRTOS移植實驗 摘自【正點原子】APM32E103最小系統板使用指南

1&#xff09;實驗平臺&#xff1a;正點原子APM32E103最小系統板 2&#xff09;平臺購買地址&#xff1a;https://detail.tmall.com/item.htm?id609294757420 3&#xff09;全套實驗源碼手冊視頻下載地址&#xff1a; http://www.openedv.com/docs/boards/xiaoxitongban 第五…

用Python制定旅行計劃

編寫一個Python腳本,用于制定旅行計劃。這個腳本將詢問關于旅行的基本問題,并根據回答生成一旅行計劃。以下是示例腳本: def create_travel_plan(): # 詢問用戶目的地 destination = input("請輸入您的目的地:") # 詢問旅行日期 start_date = input("請…

【Kuiperinfer】筆記02 GoogleTest入門

文章目錄 Google Test基本概念 編寫測試頭文件AssertionTESTTest FixtureInvoking the Tests編寫main()函數 參考 Google Test Google Test是用于編寫C測試的框架&#xff0c;支持多種類型的測試&#xff0c;而不是只有單元測試&#xff08;unit test&#xff09;。 編寫測試…

weblogic8版本修改控制臺密碼

weblogic的8.1老版本在控制臺界面上沒有修改密碼的按鈕選項&#xff0c;因此需要通過修改服務器配置文件來更新密碼。 步驟1&#xff1a; 備份域目錄下的DefaultAuthenticatorInit.ldift文件 通過find /域目錄 -name weblogic.jar 查到jar包&#xff0c;通過命令生成文件 …

css3的var()函數

css3的var()函數 變量要以兩個連字符--(橫桿)(減號)為開頭 變量可以在:root{}中定義, :root可以在css中創建全局樣式變量。通過 :root本身寫的樣式&#xff0c;相當于 html&#xff0c;但優先級比后者高。 在CSS3中&#xff0c;var()函數是一個用于插入CSS自定義屬性&#xff…

Vulhub 靶場訓練 DC-6解析

一、搭建環境 kali充當攻擊機 ip地址是&#xff1a;192.168.200.14 DC-6充當靶機 &#xff1a; IP地址暫時未知 注意&#xff1a;讓兩臺機器的使用同一種網絡適配器 二、信息收集 1、探索同網段存活的主機 ①第一種方法 arp-scan -l②第二種方法 netdiscover -i eth0 -…

Python內置函數67個語法、參數和用法詳解

要獲取Python解釋器中所有當前可用的內置函數和變量的完整列表,您可以在Python解釋器中使用dir(__builtins__)命令。這將返回一個包含所有內置函數、異常和其他內置對象的列表。 分為10類 數學運算(7): abs 絕對值divmod 商和余數max 最大min最小pow 指數冪round 取整sum 求…

npm/nodejs安裝、切換源

前言 發現自己電腦上沒有npm也沒有node很震驚&#xff0c;難道我沒寫過代碼么&#xff1f;不扯了&#xff0c;進入正題哈哈…… 安裝 一般沒有npm的話會報錯&#xff1a; 無法將“npm”項識別為 cmdlet、函數、腳本文件或可運行程序的名稱而且報這個錯&#xff0c;我們執行…

【騎行新紀元】社交風暴來襲,你準備加入騎友圈了嗎?

當你的自行車輪輕輕滑過清晨的露水&#xff0c;你是否曾想與志同道合的騎友分享這一刻的喜悅&#xff1f;騎行&#xff0c;這個曾經只是簡單運動的代名詞&#xff0c;如今正在悄然轉變。隨著科技的進步和社交平臺的發展&#xff0c;騎行不再只是一種健身方式&#xff0c;它還帶…

【機器學習】是什么?——講解

機器學習 機器學習是人工智能&#xff08;AI&#xff09;的一個子領域&#xff0c;它提供了系統通過數據學習并改進其性能的能力&#xff0c;而不需要人為進行顯式編程&#xff0c;機器學習模型利用大量的數據樣本&#xff08;訓練數據&#xff09;來學習如何識別模式和關系&a…

C-指針-010

1指針 1.1語法&#xff1a; 【基類型*指針變量名】 【int *p&a】1.2語義&#xff1a; 【基類型】&#xff1a;指針變量指向的目標的數據類型 【*】&#xff1a;表示此時定義的變量是一個指針類型的變量 【&a】&#xff1a;一塊存放著int類型數據的空間的地址 【*p】…

slot全局屬性 <slot>標簽</slot> ::slotted()偽元素 筆記240223

slot全局屬性 標簽 ::slotted()偽元素 MDN HTML全局屬性 MDN HTML全局屬性 slot MDN HTML <slot>標簽元素 MDN CSS ::slotted()為元素 MDN 使用 templates and slots <slot>標簽 <slot>標簽是的 display 是 contents 在Web開發中&#xff0c;<s…

【高德地圖】Android搭建3D高德地圖詳細教

&#x1f4d6;Android搭建3D高德地圖詳細教程 &#x1f4d6;第1章 高德地圖介紹?了解高德地圖?2D地圖與3D地圖 &#x1f4d6;第2章 搭建3D地圖并顯示?第 1 步&#xff1a;創建 Android 項目?第 2 步&#xff1a;獲取高德Key?第 3 步&#xff1a;下載地圖SDK?第 4 步&…

照片上多余的人怎么處理?這幾種方法讓你的照片更完美!

照片怎么去掉多余人像&#xff1f;這是許多攝影愛好者經常遇到的問題。有時候&#xff0c;我們拍攝了一張非常美好的照片&#xff0c;但由于某些原因&#xff0c;照片中出現了不希望出現的人物。這時候&#xff0c;我們該如何處理呢&#xff1f;下面&#xff0c;我將分享幾種常…

2.5網安學習第二階段第五周回顧(個人學習記錄使用)

本周重點 ①多進程和多線程 1、進程和線程 2、多線程爆破 ②Redis數據庫 1、Redis的使用 2、Redis持久化 3、Redis未授權免密登錄 ③嗅探和Python攻擊腳本 1、嗅探&#xff08;端口掃描和IP掃描&#xff09; 2、SCAPY的應用 3、Python攻擊腳本&#xff08;SYN半連接…

【More Effective C++】條款22:采用op+=取代op+優勢

采用operator實現operator優點&#xff1a; 降低維護成本&#xff0c;只需要維護operator即可&#xff1b;如果operator為publicoperator不需要稱為class的友元&#xff1b;通過模板的方式自動實現operator版本&#xff1b;提供兩種操作方式&#xff0c;operator效率高&#x…

計算機網絡-局域網

文章目錄 局域網局域網拓撲結構以太網以太網傳輸介質以太網時隙提高傳統以太網帶寬的途徑以太網幀格式 局域網協議IEEE 802參考模型IEEE802.2協議LLC幀格式及其控制字段LLC提供的三種服務 IEEE 802.3協議IEEE 802.4協議IEEE 802.5協議 高速局域網100M以太網千兆以太網萬兆以太網…

沖突管理最佳實踐

任何團隊都無法避免沖突&#xff0c;如何有效管理沖突&#xff0c;將沖突轉化為團隊成長和凝聚的動力&#xff0c;是任何一個團隊管理者的必修課。原文: Best Practices for Managing Conflict in Engineering Management Obie Fernandez Unsplash 沖突在任何組織中都不可避免&…