我正在使用 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))));
}
Run Code Online (Sandbox Code Playgroud)
拦截器
@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;
}),
);
}
}
Run Code Online (Sandbox Code Playgroud)
kan*_*arp 10
我能够得到做到这一点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;
}),
);
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5561 次 |
| 最近记录: |