如何在NestJS中使用Fastify设置自定义Content-Type?

时间:2020-05-31 01:41:18

标签: nestjs fastify

我在使用Fastify的NestJS中有一个应用程序。我想在响应中将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);
      })
    );
  }
}

但是,由于定义了内容类型,因此出现以下错误:

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响应的字符串表示形式。如果不是,则有效负载是一个对象。之所以发生这种情况,是因为this code in fastify永远不会运行,也永远不会将有效载荷序列化为字符串。

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

有没有办法解决这个问题?

1 个答案:

答案 0 :(得分:1)

据我了解,只要您从拦截器返回的是字符串,Nest(和Fastify)都会将其视为字符串,然后根据需要返回。我有一个示例,其中只要设置了传入的accept头来要求XML数据返回(内容协商),而Fastify可以很好地返回XML字符串,则只要您进行任何格式化您的序列化程序返回时,自定义(不同)标头应该没有问题