I'm looking to see form-data in my NestJS Guards. I've followed the tutorial, however, I'm not seeing the request body for my form-data input. I do see the body once I access a route within my controller, however.
Here's some code snippets of what I'm working with:
module.ts
...
@Module({
imports: [
MulterModule.register({
limits: { fileSize: MULTER_UPLOAD_FILESIZE_BYTES },
}),
],
controllers: [MainController],
providers: [
MainService,
AuthGuard,
],
})
...
AuthGuard.ts
import { Injectable, CanActivate, ExecutionContext } from '@nestjs/common';
import { Observable } from 'rxjs';
@Injectable()
export class AuthGuard implements CanActivate {
canActivate(
context: ExecutionContext,
): boolean | Promise<boolean> | Observable<boolean> {
const request = context.switchToHttp().getRequest(); // body is empty if form-data is used
return true;
}
}
MainController.ts
...
@Post("/upload")
@UseInterceptors(AnyFilesInterceptor())
@UseGuards(AuthGuard)
async upload(
@Body() body: UploadDTO,
@UploadedFiles() files: any[]
): Promise<any> {
console.log(body) // works as expected, whether form-data is used or not
...
}
...
Any feedback would be greatly appreciated!
Hastou :
NestJS guards are always executed before any middleware. You can use multer manually on the request object you get from the context.\n\nimport * as multer from 'multer'\n...\nasync canActivate(context: ExecutionContext): Promise<boolean> {\n const request: Request = context.switchToHttp().getRequest();\n const postMulterRequest = await new Promise((resolve, reject) => {\n multer().any()(request, {}, function(err) {\n if (err) reject(err);\n resolve(request);\n });\n });\n // postMulterRequest has a completed body\n return true;\n}\n\n\nIf you want to use the @UploadedFiles decorator, you need to clone the request object before modifying it in your guard.\n\nOf course you need to have installed the multer module with:\n\nnpm install multer\n",
2020-04-24T11:25:24