nestjs - 如何从 Nest fastify 服务器中创建的中间件发送响应?

标签 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();
  }
}

最佳答案

看起来 Fastify 抽象使用了 NodeJS vanila http 对象(这里注入(inject)的 reshttp,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()
  }
}
// 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
  }
}

关于nestjs - 如何从 Nest fastify 服务器中创建的中间件发送响应?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63811940/

相关文章:

node.js - 如何在 Nest js 中使用 fastify-adapter 配置速率限制

swagger - 在 Nest.js 项目中添加 Swagger 基本路径字段

node.js - Fastify 无法在 Docker/Kubernetes 上运行

nestjs-fastify - 如何解决nestjs fastify错误TypeError : response. status(...).json is not a function

node.js - 使用 Fastify : "@nestjs/platform-express" package is missing"error 对 NestJS 进行端到端测试

node.js - 转换 fastify-static 提供的文件的响应

node.js - NestJS e2e 测试模拟 Session 装饰器

node.js - Jest 模拟一个 toPromise 函数 - got .toPromise 不是一个函数

javascript - 测试服务时没有调用 NestJS UseFilter