header - Fastify & NestJS - 如何在拦截器中设置响应头
问题描述
我正在尝试在我的拦截器中设置响应标头,并且我发现的任何方法都没有运气。我试过了:
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)'”,其他的什么都不做。
解决方案
我的以下内容为我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 软件包的最新版本。
推荐阅读
- sql-server - 使用 SSIS 包将数据从 Oracle 传输到 SQL Server 时的性能问题
- xamarin - Xamarin.Forms 上的默认数字键盘,但允许文本(跨平台)
- reactjs - 这是存储子集合的正确方法吗?
- sql-server - 如何使用 Transact-SQL 查询获取默认数据库名称?
- data-structures - 二叉树的空指针排列
- javascript - 如何在 ng-map (AngluarJS) 中为我的信息窗口添加悬停效果?
- vb.net - Selenium MoveByOffset 只工作一次
- python - TypeError:“numpy._DTypeMeta”对象不可下标
- php - php curl响应未显示
- reactjs - 如何在 react-redux 中更新对象的状态