Fastify 和 NestJS - 如何在拦截器中设置响应标头

And*_*e C 4 header nestjs fastify

我正在尝试在拦截器中设置响应标头,但我发现的任何方法都没有运气。我试过了:

 const request = context.switchToHttp().getRequest();
 const response = context.switchToHttp().getResponse();
 <snippet of code from below>
 return next.handle();
Run Code Online (Sandbox Code Playgroud)
  • request.res.headers['my-header'] = 'xyz'
  • response.header('my-header', 'xyz')
  • response.headers['my-header'] = 'xyz'
  • response.header['my-header'] = 'xyz'

没有运气。第一个选项表示 res 未定义,第二个选项表示“无法读取未定义的属性‘Symbol(fastify.reply.headers)’”,其他选项则不执行任何操作。

Jay*_*iel 6

FastifyAdapter我的以下工作为我工作main.ts

\n\n

标头拦截器

\n\n
@Injectable()\nexport class HeaderInterceptor implements NestInterceptor {\n  intercept(context: ExecutionContext, next: CallHandler): Observable<any> {\n    return next.handle().pipe(\n      tap(() => {\n        const res = context.switchToHttp().getResponse<FastifyReply<ServerResponse>>();\n        res.header(\'foo\', \'bar\');\n      })\n    );\n  }\n}\n
Run Code Online (Sandbox Code Playgroud)\n\n

使用.getResponse<FastifyReply<ServerResponse>>()为我们提供了正确的输入方式。

\n\n

应用程序模块

\n\n
@Module({\n  imports: [],\n  controllers: [AppController],\n  providers: [\n    AppService,\n    {\n      provide: APP_INTERCEPTOR,\n      useClass: HeaderInterceptor,\n    },\n  ],\n})\nexport class AppModule {}\n
Run Code Online (Sandbox Code Playgroud)\n\n

将拦截器绑定到整个服务器

\n\n

curl命令

\n\n
\xe2\x96\xb6 curl http://localhost:3000 -v\n* Rebuilt URL to: http://localhost:3000/\n*   Trying 127.0.0.1...\n* TCP_NODELAY set\n* Connected to localhost (127.0.0.1) port 3000 (#0)\n> GET / HTTP/1.1\n> Host: localhost:3000\n> User-Agent: curl/7.54.0\n> Accept: */*\n> \n< HTTP/1.1 200 OK\n< foo: bar\n< content-type: text/plain; charset=utf-8\n< content-length: 12\n< Date: Thu, 14 May 2020 14:09:22 GMT\n< Connection: keep-alive\n< \n* Connection #0 to host localhost left intact\nHello World!% \n
Run Code Online (Sandbox Code Playgroud)\n\n

正如您所看到的,响应返回时带有标头,foo: bar这意味着拦截器添加了预期的内容。

\n\n

查看您的错误,看来您的第二次尝试实际上可能response.headers(\'my-header\', \'xyz)。不管怎样,上面的内容对我的nest new应用程序以及最新版本的 Nest 软件包都有效。

\n