【发布时间】: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 是一个供您轻松复制问题的存储库。
有没有办法解决这个问题?
【问题讨论】: