我希望在NestJS Guards中查看表单数据。我有followed the tutorial,但是看不到表单数据输入的请求正文。但是,一旦在控制器中访问了一条路线,我便会看到尸体。
以下是我正在使用的代码片段:
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
...
}
...
任何反馈将不胜感激!
答案 0 :(得分:0)
NestJS防护始终在任何中间件之前执行。您可以在从上下文中获取的请求对象上手动使用multer。
import * as multer from 'multer'
...
async canActivate(context: ExecutionContext): Promise<boolean> {
const request: Request = context.switchToHttp().getRequest();
const postMulterRequest = await new Promise((resolve, reject) => {
multer().any()(request, {}, function(err) {
if (err) reject(err);
resolve(request);
});
});
// postMulterRequest has a completed body
return true;
}
如果要使用@UploadedFiles装饰器,则需要克隆请求对象,然后才能在防护中对其进行修改。
当然,您需要使用以下方法安装multer模块:
npm install multer