首页 > 解决方案 > Fastify & NestJS - 如何在拦截器中设置响应头

问题描述

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

 const request = context.switchToHttp().getRequest();
 const response = context.switchToHttp().getResponse();
 <snippet of code from below>
 return next.handle();

没有运气。第一个选项说 res 是未定义的,第二个“无法读取未定义的属性 'Symbol(fastify.reply.headers)'”,其他的什么都不做。

标签: headernestjsfastify

解决方案


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

标头拦截器

@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>>()为我们提供了正确的类型。

应用模块

@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 软件包的最新版本。


推荐阅读