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