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

时间:2020-05-14 11:59:53

标签: header nestjs fastify

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

 const request = context.switchToHttp().getRequest();
 const response = context.switchToHttp().getResponse();
 <snippet of code from below>
 return next.handle();
  • 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)'”,其他选项则什么都不做。

1 个答案:

答案 0 :(得分:0)

FastifyAdapter中使用main.ts时,我需要进行以下工作:

HeaderInterceptor

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

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

AppModule

@Module({
  imports: [],
  controllers: [AppController],
  providers: [
    AppService,
    {
      provide: APP_INTERCEPTOR,
      useClass: HeaderInterceptor,
    },
  ],
})
export class AppModule {}

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

curl命令

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

如您所见,响应以标头foo: bar返回,表示拦截器添加了预期的内容。

查看您的错误,看来您第二次尝试可能实际上是response.headers('my-header', 'xyz)。无论如何,以上内容都可以在nest new应用程序以及最新版的Nest软件包中为我工作。