nestjs - 如何在 NestJS Controller 中获取表单数据

标签 nestjs form-data

我正在将现有的基于 PHP 的 API 重写为 NestJS(同时学习 NestJS)。

重要的一点是我无法触及前端服务,因此我需要确保新应用程序可以处理前端发送给它的任何内容,并使用与原始 api 相同的数据结构进行响应。

这就是我碰壁的地方。前端应用程序提交的所有内容都采用formdata 的形式。 NestJS 文档中给出的唯一示例与获取上传的文件有关,但与它可能附带的任何其他数据无关。到目前为止,Google 搜索并没有太大帮助。

我找到的最好的是这篇 SO 帖子 Accept form-data in Nest.js但我仍然无法获取提交的数据。

提交的数据:

enter image description here

> POST /public/login HTTP/1.1
> Host: localhost:3000
> Content-Type: multipart/form-data;
> Accept: */*
> Content-Length: 196

| Content-Disposition: form-data; name="login"
| sampleuser
| Content-Disposition: form-data; name="password"
| userpassword

我的 authentication.controller.ts 的内容:

import { Controller, Post, Body, Get, Param, Patch, Delete, Req, Header, UseInterceptors, } from "@nestjs/common";

@Controller()
export class AuthenticationController {

    constructor() { }

    @Post('public/login')
    @UseInterceptors()
    login(@Body() body) {
        console.log(body);
    }
}

日志结果只是{}

我在这里遗漏/做错了什么。我是否需要安装一些额外的 npm 包才能完成这项工作?获得这样的通用数据肯定不会那么困难。有人能给我指出正确的方向或一个可行的例子吗。

谢谢

最佳答案

当提供表单数据时(主要用于文件上传,或者至少,这是我应用此内容类型的唯一方式),我认为 NestJS 提供了相同的方法。所以,我建议使用 FileInterceptor

试试这个:

import { Controller, Post, Body, Get, Param, Patch, Delete, Req, Header, UseInterceptors, } from "@nestjs/common";
import { FileInterceptor } from '@nestjs/platform-express';

@Controller()
export class AuthenticationController {

    constructor() { }

    @Post('public/login')
    // You're not actually providing a file, but the interceptor will expect "form data" 
    // (at least in a high level, that's how I think this interceptor works)
    @UseInterceptors(FileInterceptor('file'))
    login(@Body() body) {
        console.log(body);
    }
}

关于nestjs - 如何在 NestJS Controller 中获取表单数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69282724/

相关文章:

node.js - Nestjs 中多个 graphql 解析器实现的问题

nestjs - 如何从 Nest fastify 服务器中创建的中间件发送响应?

typescript - 如何借助 Automapper (TypeScript) 映射充满不同 DTO 的数组条目?

javascript - 以angular2 : Body (FormData) empty上传文件

php - FormData 发送文件但 $_FILE 为空

NestJS:无法读取未定义的属性 "' createObjectLiteralExpression'"

node.js - 使用 AWS Parameter Store 的 NestJs TypeORM 配置

javascript - 使用 transformRequest 将 JSON 转换为 FormURL 编码数据

Angular 如何以编程方式发送表单数据

javascript - 无法发送多个表单字段 formdata dropzone.js