NestJS:在Guards中接收表单数据吗? [英] NestJS: Receive form-data in Guards?
问题描述
我希望在NestJS Guards中查看表单数据.我已经按照该教程进行了操作,但是,我没有看到请求正文我的表单数据输入.但是,一旦在控制器中访问了一条路线,我便会看到尸体.
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
...
}
...
任何反馈将不胜感激!
推荐答案
NestJS防护始终在任何中间件之前执行.您可以在从上下文中获取的请求对象上手动使用multer.
NestJS guards are always executed before any middleware. You can use multer manually on the request object you get from the context.
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装饰器,则需要克隆请求对象,然后才能在防护中对其进行修改.
If you want to use the @UploadedFiles decorator, you need to clone the request object before modifying it in your guard.
当然,您需要使用以下方法安装multer模块:
Of course you need to have installed the multer module with:
npm install multer
这篇关于NestJS:在Guards中接收表单数据吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!