【问题标题】:How to get the form data inside NestJS controller如何在 NestJS 控制器中获取表单数据
【发布时间】:2021-09-22 10:47:56
【问题描述】:

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

重要的是我不能接触前端服务,所以我需要确保新应用可以处理前端发送给它的任何东西,并以与原始 api 相同的数据结构进行响应。

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

我发现最好的是这个 SO 帖子 Accept form-data in Nest.js 但我仍然无法获得提交的数据。

提交数据:

> 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 form-data


    【解决方案1】:

    在提供表单数据时(主要用于文件上传,或者至少这是我应用此内容类型的唯一方式),我认为 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);
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2017-08-06
      • 1970-01-01
      • 1970-01-01
      • 2020-05-06
      • 1970-01-01
      • 2012-02-17
      • 2018-06-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多