Nestjs req。邮政方法的body在等待arraybuffer时是空的/未定义的

发布于 2025-02-13 23:28:12 字数 2047 浏览 5 评论 0原文

我试图将文件从客户端(Angular)发送到Nestjs,就像现在使用Java-springboot API一样。

我正在使用Nestjs中的Post方法,但是,不幸的是,我无法从身体中获取任何数据:

这是代码:

  @Post('/uploadExportFile')
  uploadAttachment(@Req() req: Request, @Body() attachment: ArrayBuffer): any {
    console.log(attachment);
    return {};
  }

content-type设置在客户端的标题中,我不确定是否需要设置内容类型那里 ?内容类型取决于文件模拟物应该是(application/pdf/png/jpeg)。

req.body不确定

我需要处理的文件是再次将其更改回base64(在Angular中,它在base64中),但是Java API仅消耗byte []因此,我需要像Fe一样保留它。

任何建议在此“简单”代码中有什么问题?

**编辑**

=======↓编辑↓====

解决方案:request.body不确定的是:

NESTJS用作默认的身体JSONBODY,因此在这种情况下,您必须覆盖特定路线您想使用原始体,如果使用了JSONBODY的原始体,则请求的主体并不定义,并且包含ArrayBuffer。

您需要做的就是这样的事情;

创建RAWBODY MIDERDWARE RAW-BODY.MIDDLEWARE.TS

import { Injectable, NestMiddleware } from '@nestjs/common';
import { Request, Response } from 'express';
import * as bodyParser from 'body-parser';

@Injectable()
export class RawBodyMiddleware implements NestMiddleware {
    use(req: Request, res: Response, next: () => any) {
        bodyParser.raw({type: '*/*'})(req, res, next);
    }
}

app.module.ts

export class AppModule implements NestModule {
    public configure(consumer: MiddlewareConsumer): void {
        consumer
            .apply(RawBodyMiddleware)
            .forRoutes({
                path: '/uploadExportFile',
                method: RequestMethod.POST,
            })
            .apply(JsonBodyMiddleware)
            .forRoutes('*');
    }
}

,您需要在main.ts.ts中禁用BodyParser,

const app = await NestFactory.create(AppModule, { bodyParser: false })

以新版本的新版本Nestjs被引入新选项RAW-BODY,但我没有可能测试 https://docs.nestjs.com/faq/faq/faq/raw-body-body-body-bodrow-bod--body < /a>

I am trying to send file from Client (Angular) to the NestJS same way like it is working now with Java-springboot API.

I am using POST method in NestJS but, unfortunatelly I am not able to got any data from the body :

here is the code :

  @Post('/uploadExportFile')
  uploadAttachment(@Req() req: Request, @Body() attachment: ArrayBuffer): any {
    console.log(attachment);
    return {};
  }

content-type is set in header on Client side, I am not sure if I need to set content-types there ? Content type depends on file mimetype it should be (application/pdf/png/jpeg)..not multiform or what I need to do to achieve that attachment object will not return empty {} .

req.body is undefined

What I need to do with that file is to again change it back to Base64 (in angular it is in Base64) but Java API consumes only byte[] so I need to keep that like it is on FE.

any suggestions what is wrong in this "simple" code?

** EDIT **

====↓ EDIT ↓====

Solution: request.body is undefined is:

NestJS use as default body jsonBody, so in that case you have to override for specific routes that you want to use raw-body, and if raw-body is used insted of jsonBody, then the body from request is not undefined and it contain ArrayBuffer.

What you need to do is something like this;

Create rawBody middleware raw-body.middleware.ts

import { Injectable, NestMiddleware } from '@nestjs/common';
import { Request, Response } from 'express';
import * as bodyParser from 'body-parser';

@Injectable()
export class RawBodyMiddleware implements NestMiddleware {
    use(req: Request, res: Response, next: () => any) {
        bodyParser.raw({type: '*/*'})(req, res, next);
    }
}

app.module.ts

export class AppModule implements NestModule {
    public configure(consumer: MiddlewareConsumer): void {
        consumer
            .apply(RawBodyMiddleware)
            .forRoutes({
                path: '/uploadExportFile',
                method: RequestMethod.POST,
            })
            .apply(JsonBodyMiddleware)
            .forRoutes('*');
    }
}

and you need to disable bodyparser in main.ts

const app = await NestFactory.create(AppModule, { bodyParser: false })

in new version of NestJS is introduced new option raw-body but I have no possibility to test that https://docs.nestjs.com/faq/raw-body#raw-body

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

南冥有猫 2025-02-20 23:28:12

Frist Thing发送content-type 应用程序/x-www-form-urlencoded
并确保您添加 useInterceptors fileinterceptor
您可以导入FileInterceptor,

如果需要获得缓冲区,请尝试使用file.buffer

import {FileInterceptor} from "@nestjs/platform-express";
@Post('upload')
@UseInterceptors(FileInterceptor('file'))
    async upload(@Req() request: RequestWithUser, @UploadedFile() file) {
        if (!file) {
            throw new HttpException('File is required', HttpStatus.BAD_REQUEST);
        }
        // you have file
        return await this.storageService.upload(file, request.user);
    }

frist thing send the content-type application/x-www-form-urlencoded
and sure you have add UseInterceptors Like FileInterceptor
you can import FileInterceptor

if you need to get buffer try use file.buffer

import {FileInterceptor} from "@nestjs/platform-express";
@Post('upload')
@UseInterceptors(FileInterceptor('file'))
    async upload(@Req() request: RequestWithUser, @UploadedFile() file) {
        if (!file) {
            throw new HttpException('File is required', HttpStatus.BAD_REQUEST);
        }
        // you have file
        return await this.storageService.upload(file, request.user);
    }
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文