Fastify & NestJS - How to set response headers in interceptor

淺唱寂寞╮ 提交于 2021-01-28 05:35:02

问题


I'm trying to set the response headers in my interceptor, and have had no luck with any method I've found yet. I've tried:

 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'

with no luck. The first option says that res is undefined, the second "Cannot read property 'Symbol(fastify.reply.headers)' of undefined", and the others just do nothing.


回答1:


I have the following working for me with the FastifyAdapter in my 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');
      })
    );
  }
}

Using .getResponse<FastifyReply<ServerResponse>>() gives us the correct typings to work with.

AppModule

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

Bind the interceptor to the entire server

curl Command

▶ 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!% 

As you can see, the response comes back with the header foo: bar meaning the interceptor added what was expected.

Looking at your error, it looks like your second attempt may have actually been response.headers('my-header', 'xyz). Whatever the case, the above is working for me on a nest new application, and on the latest version of Nest's packages.



来源:https://stackoverflow.com/questions/61796828/fastify-nestjs-how-to-set-response-headers-in-interceptor

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!