NestJs - 如何在拦截器上获取请求正文

And*_*eri 9 javascript node.js nestjs

在进入我的控制器之前,我需要在我的拦截器上获取请求正文:

import { Injectable, NestInterceptor, ExecutionContext, HttpException, HttpStatus } from '@nestjs/common';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';

@Injectable()
export class ExcludeNullInterceptor implements NestInterceptor {
    intercept(context: ExecutionContext, call$: Observable<any>): Observable<any> {
        // How can I get the request body here?
        // Need to be BEFORE the Controller exec
    }
}
Run Code Online (Sandbox Code Playgroud)

Kim*_*ern 15

在您的拦截器中,您可以执行以下操作:

async intercept(context: ExecutionContext, stream$: Observable<any>): Observable<any> {
    const body = context.switchToHttp().getRequest().body;
    // e.g. throw an exception if property is missing
Run Code Online (Sandbox Code Playgroud)

或者,您可以使用可以直接访问请求的中间件:

(req, res, next) => {
Run Code Online (Sandbox Code Playgroud)