NestJS拦截器-如何在响应结束后获取响应状态码和正文



在拦截器中可以通过context.getArgByIndex(1)获取响应状态。这段代码记录了一个我想要的403状态码。但是这个代码context.getArgByIndex(1).statusCode返回给我状态201。我从服务中抛出状态403

拦截器代码

import { Injectable, NestInterceptor, ExecutionContext, CallHandler } from '@nestjs/common';
import { Observable } from 'rxjs';
import { map, tap } from 'rxjs/operators';
import { LogsService } from './logs.service';
@Injectable()
export class LogsInterceptor implements NestInterceptor {
constructor( private readonly logService: LogsService ) {}
intercept(context: ExecutionContext, next: CallHandler): Observable<any> {


this.logService.constructorData(context)
console.log(context.getArgByIndex(0)) --- **This code logs the correct status**
console.log(context.getArgByIndex(0).statusCode) --- **This code logs status 201**
return next.handle()    
}
}

为测试

抛出错误的服务代码
async findAll(): Promise<PodsDto[]> {
throw new ForbiddenException()
return this.PodsRepository.find()
}

也许这不是一个好的选择,但它是有效的。

拦截器代码

@Injectable()
export class LogsInterceptor implements NestInterceptor {
constructor( private readonly yourService: yourService) {}
intercept(context: ExecutionContext, next: CallHandler): Observable<any> {

const ctx = context.switchToHttp();
const response = ctx.getResponse();
response.on('close', ()=>{
this.yourService.yourFunction(context)
})
return next.handle()
}
}
V2

如果你需要读取响应体

@Injectable()
export class ActionLogsInterceptor implements NestInterceptor {
constructor( private readonly yourService: yourService) {}
intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
const ctx = context.switchToHttp();
return next
.handle()
.pipe(
tap((responseBody) =>  this.yourService.yourFunction(context, responseBody)),
);
}
}

最新更新