Nest.js 表单数据的空请求体

huangapple go评论92阅读模式
英文:

Nest.js empty Body for form data

问题

我有一个简单的控制器,在这个控制器中有这个端点:

@Post('/temp')
async asdf(
  @Body() form: Record<string, string>,
  @Res({ passthrough: true }) response: Response,
) {
  this.logger.debug(JSON.stringify(form));
  await response.json({ ok: true, form: JSON.stringify(form) });
}

当我尝试使用cURL或浏览器在上面POST一些表单数据时,对象form为空。

例如:

curl -X POST http://localhost:4000/mycontroller/temp -H "Content-Type: application/x-www-form-urlencoded" -d "param1=value1&param2=value2"

结果是

{"ok":true,"form":"{}"}

其他控制器正常工作;我看不出我的控制器和其他端点之间的任何区别。

我做错了什么或者漏掉了什么?

英文:

I have a simple controller, in this controller I have this endpoint

@Post(&#39;/temp&#39;)
async asdf(
  @Body() form: Record&lt;string, string&gt;,
  @Res({ passthrough: true }) response: Response,
) {
  this.logger.debug(JSON.stringify(form));
  await response.json({ ok: true, form: JSON.stringify(form) });
}

When I try to POST some form data on it, using cURL or the browser, the object form is empty.

Example:

curl -X POST http://localhost:4000/mycontroller/temp -H &quot;Content-Type: application/x-www-form-urlencoded&quot; -d &quot;param1=value1&amp;param2=value2&quot;

Results in

> {"ok":true,"form":"{}"}

Other controllers work; I can't see any difference between my controller and the endpoint to others.

What I'm doing wrong or missing?

答案1

得分: 1

如果您使用表单数据,您需要实现一个表单数据解析器,比如busboymulter。Nest通过FileInterceptor及其变体与multerexpress集成。这将强制multer解析请求。如果您不使用任何文件,只使用表单数据格式,我相信有一个NoFileInterceptor或类似的东西。


看起来没有NoFileInterceptor。您可以使用AnyFileInterceptor代替,并忽略req.files,只要注意如果multer需要解析一组非常恶意的文件,可能会导致服务器崩溃。

英文:

If you're using form data you need to implement a form data parser, like busboy or multer. Nest integrates with multer and express already via the FileInterceptor and its variants. This will force multer to parse the request. If you don't use any files, just the form data format, I believe there is a NoFileInterceptor or similar.


Looks like there is no NoFileInterceptor. You could use AnyFileInterceptor instead and ignore the req.files, just be aware it could end up having your server taken down if a really nasty set of files comes in for multer to parse

huangapple
  • 本文由 发表于 2023年6月2日 01:38:06
  • 转载请务必保留本文链接:https://go.coder-hub.com/76384393.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定