英文:
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¶m2=value2"
结果是
{"ok":true,"form":"{}"}
其他控制器正常工作;我看不出我的控制器和其他端点之间的任何区别。
我做错了什么或者漏掉了什么?
英文:
I have a simple controller, in this controller I have this endpoint
@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) });
}
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 "Content-Type: application/x-www-form-urlencoded" -d "param1=value1&param2=value2"
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
如果您使用表单数据,您需要实现一个表单数据解析器,比如busboy
或multer
。Nest通过FileInterceptor
及其变体与multer
和express
集成。这将强制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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论