如何在 NestJS 中使用 fastify 设置自定义内容类型?

How to set a custom Content-Type with fastify in NestJS?

我在 NestJS 中有一个使用 Fastify 的应用程序。我想在我的回复中将 Content-Type 设置为 application/hal+json。我在 NestJS 拦截器中有以下代码:

@Injectable()
export class SampleInterceptor implements NestInterceptor {
  intercept(context: ExecutionContext, next: CallHandler): Observable<any> {

    context.switchToHttp().getResponse()
      .header('Content-Type', 'application/hal+json; charset=utf-8');

    return next.handle().pipe(
      map((data) => {
        const serializer = MyCustomSerializer();
        return serializer.serialize(data);
      })
    );
  }
}

但是,我有以下错误,因为我定义了 Content-Type:

FastifyError [FST_ERR_REP_INVALID_PAYLOAD_TYPE]: FST_ERR_REP_INVALID_PAYLOAD_TYPE: Attempted to send payload of invalid type 'object'. Expected a string or Buffer.
    at onSendEnd (/home/user/Projects/nestjs-fastify-sample/node_modules/fastify/lib/reply.js:363:11)
    at onSendHook (/home/user/Projects/nestjs-fastify-sample/node_modules/fastify/lib/reply.js:325:5)
    at _Reply.Reply.send (/home/user/Projects/nestjs-fastify-sample/node_modules/fastify/lib/reply.js:151:3)
    at FastifyAdapter.reply (/home/user/Projects/nestjs-fastify-sample/node_modules/@nestjs/platform-fastify/adapters/fastify-adapter.js:37:25)
    at RouterResponseController.apply (/home/user/Projects/nestjs-fastify-sample/node_modules/@nestjs/core/router/router-response-controller.js:10:36)
    at /home/user/Projects/nestjs-fastify-sample/node_modules/@nestjs/core/router/router-execution-context.js:163:48
    at processTicksAndRejections (internal/process/task_queues.js:85:5)
    at async /home/user/Projects/nestjs-fastify-sample/node_modules/@nestjs/core/router/router-execution-context.js:46:13
    at async Object.<anonymous> (/home/user/Projects/nestjs-fastify-sample/node_modules/@nestjs/core/router/router-proxy.js:8:17)

经过一些调查,我注意到如果我没有定义 Content-Type,则有效负载是我的 JSON 响应的字符串表示形式。如果不是,则有效载荷是一个对象。发生这种情况是因为 fastify 中的 this code 从不运行并且从不将有效负载序列化为字符串。

Here 是一个让您轻松复制问题的存储库。

有办法解决这个问题吗?

根据我的理解,只要你从拦截器中 return 是一个字符串,Nest(和 Fastify)就会把它当作一个字符串来处理,并且 return 你想怎么处理就怎么处理。我有一个例子,只要传入的 accept header 设置为请求 XML 数据返回(内容negotiation) 和 Fastify returning 它就好了,所以只要你 strinigfy 无论你的序列化器 returns,你不应该有一个自定义的问题(不同的)header