乐闻世界logo
搜索文章和话题

How to use a route specific middleware of express in Nestjs?

1个答案

1

In NestJS, you can use Express middleware at the module, controller, or individual route level. NestJS is fundamentally built on top of Express (by default, but Fastify can also be used), so you can directly leverage Express middleware. Here are some approaches for implementing Express route-specific middleware:

Global Middleware

To apply middleware across the entire application, register it globally in the main.ts file:

typescript
import { NestFactory } from '@nestjs/core'; import { AppModule } from './app.module'; import * as helmet from 'helmet'; // A security middleware async function bootstrap() { const app = await NestFactory.create(AppModule); app.use(helmet()); // Apply helmet middleware globally await app.listen(3000); } bootstrap();

Module-Level Middleware

At the Module level, implement the NestModule interface and configure middleware in the configure method:

typescript
import { Module, NestModule, MiddlewareConsumer } from '@nestjs/common'; import { loggerMiddleware } from './logger.middleware'; @Module({ // ... other configuration such as controllers and providers }) export class AppModule implements NestModule { configure(consumer: MiddlewareConsumer) { consumer .apply(loggerMiddleware) .forRoutes('cats'); // Apply middleware exclusively to the 'cats' route } }

Controller-Level Middleware

For middleware limited to specific routes within a controller, configure it in the controller's constructor:

typescript
import { Controller, Get, UseMiddleware } from '@nestjs/common'; @Controller('cats') export class CatsController { @Get() @UseMiddleware(loggerMiddleware) // Apply middleware using decorator findAll() { // ... route handling logic } }

Note that the @UseMiddleware decorator is not an official NestJS API; this is for illustrative purposes only. In NestJS, you can use @UseGuards, @UseInterceptors, @UsePipes, and @UseFilters for related functionality. For middleware, it's typically registered at the Module level via the configure method. However, if you need to directly integrate Express middleware within route handlers, use this approach:

typescript
import { Controller, Get, Req, Res, Next } from '@nestjs/common'; import { Request, Response, NextFunction } from 'express'; @Controller('cats') export class CatsController { @Get() findCat(@Req() req: Request, @Res() res: Response, @Next() next: NextFunction) { loggerMiddleware(req, res, next); // ... after invoking next(), route handling logic continues } }

By applying these methods, you can implement Express route-specific middleware at appropriate hierarchical levels in your NestJS application. Always consider middleware scope and execution order to ensure application security and efficiency.

2024年6月29日 12:07 回复

你的答案