【问题标题】:How to set a custom Content-Type with fastify in NestJS?如何在 NestJS 中使用 fastify 设置自定义 Content-Type?
【发布时间】:2020-09-18 11:29:25
【问题描述】:

我在 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 是一个供您轻松复制问题的存储库。

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

【问题讨论】:

    标签: nestjs fastify


    【解决方案1】:

    根据我的理解,只要你从拦截器返回的是一个字符串,Nest(和 Fastify)就会把它当作一个字符串来处理,并根据你的需要返回它。我有一个例子,我返回一个 XML 字符串,只要传入的 accept 标头设置为要求返回 XML 数据(内容协商)并且 Fastify 可以很好地返回它,只要你对你的序列化程序进行 strinigfy返回,您不应该对自定义(不同)标题有问题

    【讨论】:

    • 嗨。谢谢你的时间。不幸的是,如果您在使用 Fastify 时更改 Content-Type,这将不起作用。我在我的答案中添加了一个复制包。您可以根据自述文件克隆存储库并运行应用程序。
    • 我要指出我的第一句话只要你从拦截器返回的是一个字符串 Nest 和 Fastify 不会做任何数据处理并允许你返回任何你想要的。这就是我如何让它毫无问题地返回 XML。如果您将return data 更改为return JSON.stringify(data),我保证它将返回您所期望的内容而不会出错。
    • 谢谢!你说得对。我以前不明白你的论点。
    猜你喜欢
    • 2023-03-16
    • 2015-03-12
    • 1970-01-01
    • 2017-02-19
    • 1970-01-01
    • 2020-08-30
    • 1970-01-01
    • 2011-01-04
    • 2011-09-05
    相关资源
    最近更新 更多