Faa*_*han 4 nestjs fastify nestjs-fastify
我用 Fastify 创建了一个 NestJs 项目,并为其创建了一个中间件,但我不知道如何向客户端发送响应,类似于我们在 Express 中的做法,任何帮助将不胜感激,谢谢!,这是我的中间件代码:
import {
Injectable,
NestMiddleware,
HttpException,
HttpStatus,
} from '@nestjs/common';
@Injectable()
export class LoggerMiddleware implements NestMiddleware {
use(req: any, res: any, next: Function) {
console.log('Request...', res);
// throw new HttpException('Forbidden', HttpStatus.FORBIDDEN);
next();
}
}
Run Code Online (Sandbox Code Playgroud)
看起来Fastify抽象使用 NodeJS vanilahttp对象(res这里注入的是http,ServerResponse)
// app.middleware.ts
import { Injectable, NestMiddleware } from '@nestjs/common';
import { ServerResponse, IncomingMessage } from 'http';
@Injectable()
export class AppMiddleware implements NestMiddleware {
use(req: IncomingMessage, res: ServerResponse, next: Function) {
res.writeHead(200, { 'content-type': 'application/json' })
res.write(JSON.stringify({ test: "test" }))
res.end()
}
}
Run Code Online (Sandbox Code Playgroud)
// app.module.ts
import { Module, MiddlewareConsumer, RequestMethod } from '@nestjs/common';
import { AppController } from './app.controller';
import { AppMiddleware } from './app.middleware';
@Module({
imports: [],
controllers: [AppController],
providers: [],
})
export class AppModule {
configure(consumer: MiddlewareConsumer) {
consumer
.apply(AppMiddleware)
.forRoutes({ path: '*', method: RequestMethod.ALL }); // apply on all routes
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7399 次 |
| 最近记录: |