I. About Nextjs middleware
Middleware is a set of operations done before or after a route is matched. In middleware, if you want to match down, you write next().
Nestjs middleware is actually equivalent to Express middleware. Here are the middleware features described in the official Express documentation:
Middleware functions can perform the following tasks:
Execute any code. Make changes to the request and response objects. End the request-response cycle. Call the next middleware function in the stack. If the current middleware function does not end the request-response cycle, it must call next() to pass control to the next intermediary function. Otherwise, the request will be suspended.Copy the code
Nest middleware can be a function or a class with the @Injectable() decorator.
Second, Nestjs creates using middleware
1. Create middleware
nest g middleware init
Copy the code
import { Injectable, NestMiddleware } from '@nestjs/common'; @Injectable() export class InitMiddleware implements NestMiddleware { use(req: any, res: any, next: () => void) { console.log('init'); next(); }}Copy the code
2. Configure middleware
Inherit NestModule from app.module.ts and configure middleware
export class AppModule implements NestModule { configure(consumer: MiddlewareConsumer) {
consumer.apply(InitMiddleware)
.forRoutes({ path: '*', method: RequestMethod.ALL })
.apply(NewsMiddleware)
.forRoutes({ path: 'news', method: RequestMethod.ALL })
.apply(UserMiddleware)
.forRoutes({ path: 'user', method: RequestMethod.GET },{ path: '', method: RequestMethod.GET });
}}
Copy the code
Three, multiple middleware
consumer.apply(cors(), helmet(), logger).forRoutes(CatsController);
Copy the code
Functional middleware
export function logger(req, res, next) { console.log(`Request... `); next(); };Copy the code
Global middleware
const app = await NestFactory.create(ApplicationModule);
app.use(logger);
await app.listen(3000);
Copy the code