【问题标题】:Fastify & NestJS - How to set response headers in interceptorFastify & NestJS - 如何在拦截器中设置响应头
【发布时间】:2020-08-30 22:57:11
【问题描述】:

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

 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)'”,其他选项什么都不做。

【问题讨论】:

    标签: header nestjs fastify


    【解决方案1】:

    我在main.ts 中使用FastifyAdapter 为我工作:

    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&lt;FastifyReply&lt;ServerResponse&gt;&gt;() 可以为我们提供正确的类型。

    应用模块

    @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 软件包的最新版本上对我有用。

    【讨论】:

    • 我意识到我做错了什么,response.headers 确实有效。谢谢
    猜你喜欢
    • 2023-03-16
    • 2021-11-22
    • 1970-01-01
    • 1970-01-01
    • 2022-10-14
    • 2021-04-10
    • 2016-10-14
    • 2014-12-25
    • 1970-01-01
    相关资源
    最近更新 更多