nestjs - 如何使用 NestJs 中的拦截器修改来自 PUT 的请求和响应
问题描述
我正在使用 NestJs。我在我的控制器中使用拦截器来处理 PUT 请求。
我想在 PUT 请求之前更改请求正文,并且我想更改 PUT 请求返回的响应正文。如何做到这一点?
在 PUT 中使用
@UseInterceptors(UpdateFlowInterceptor)
@Put('flows')
public updateFlow(@Body() flow: Flow): Observable<Flow> {
return this.apiFactory.getApiService().updateFlow(flow).pipe(catchError(error =>
of(new HttpException(error.message, 404))));
}
拦截器
@Injectable()
export class UpdateFlowInterceptor implements NestInterceptor {
public intercept(_context: ExecutionContext, next: CallHandler): Observable<FlowUI> {
// how to change request also
return next.handle().pipe(
map(flow => {
flow.name = 'changeing response body';
return flow;
}),
);
}
}
解决方案
我能够通过以下代码来做到这request
一点ExecutionContext
。
@Injectable()
export class UpdateFlowInterceptor implements NestInterceptor {
public intercept(_context: ExecutionContext, next: CallHandler): Observable<FlowUI> {
// changing request
let request = _context.switchToHttp().getRequest();
if (request.body.name) {
request.body.name = 'modify request';
}
return next.handle().pipe(
map(flow => {
flow.name = 'changeing response body';
return flow;
}),
);
}
}
推荐阅读
- dart - Flutter - 长按弹出菜单
- javascript - 制作ul li下拉过滤器
- aws-amplify - 错误:uncaughtException:provider.getConfiguredPinpointClient 不是函数
- php - 当元值为 NULL 为空时,如何优化我的代码以返回空?
- python - 如何使这个特定的 if 语句(在嵌套的 if 中)起作用?
- python - 我可以使用一个导入语句来替换 4 吗?
- php - PHP:将str转换为数字
- python - PyTables vs Matlab HDF5 读取时间
- reactjs - 在表单中使用函数式 setState
- javascript - .ajax() 不想读取 xml 数据