Albert
Albert

Reputation: 2664

Empty request body in a nestjs guard (bug?)

    @Post()
    @UseGuards(
        CategoryVerificationGuard,
        VerboseAuthGuard,
        UniqueEntryTitleGuard,
    )
    @UseInterceptors(FileFieldsInterceptor([
        { name: AttachmentsName.IMAGES, maxCount: AttachmentMaxCount.IMAGES },
    ]))
    public async createEntry(@UploadedFiles() attachedFiles: IUploadFile[],
                             @Body() createEntryBodyDto: CreateEntryBodyDto,
                             @Headers('authorization') authHeader: string): Promise<any> {
        return this.entryService.create(getUserIdByAuthHeader(authHeader), {attachedFiles, ...createEntryBodyDto});
    }

The code for the guard:

@Injectable()
export class CategoryVerificationGuard implements CanActivate {
    constructor(
        // private readonly categoriesService: CategoriesService,
    ) {}

    public async canActivate(ctx: ExecutionContext): Promise<boolean> {
        const request = ctx.switchToHttp().getRequest<Request>();
        const requestBody: IConfirmationCodeValidation = request.body;
        const requestHeaders: IncomingHttpHeaders = request.headers;

        console.log('BODY', requestBody);
        console.log('HEADERS', requestHeaders);
        return true;
    }
}

If I set multipart form I get empty body. Why does it happen? Looks like a bug.

P.S.

It is however possible to get access to headers but body is empty for some reason...

Upvotes: 1

Views: 2955

Answers (1)

Jay McDoniel
Jay McDoniel

Reputation: 70061

Guards are activated before interceptors are. In this case, multipart form data is handled by the FileInterceptor or FilesInterceptor (depending on how many files are sent in). Because the body is assigned in the interceptor (due to when multer is called), this is the intended functionality, as the body has not been parsed by the proper middleware. You can decide to call multer() on your own in your main.ts if you prefer, depending on the incoming header type.

Upvotes: 3

Related Questions