NodeJS 使用Postman对Express后端的HTTP请求引发意外的表单结尾(多部分表单数据)

soat7uwm  于 2023-01-08  发布在  Node.js
关注(0)|答案(2)|浏览(283)

我正在使用postman向我的API后端(在google函数中)发送一个multipart/form-data请求。在请求中,我发送了两个字段和一个文件。请求由Multer/busboy处理,它会抛出错误- Unexpected end of the form。下面是我从 Postman 那里得到的原始格式的请求:

POST /app/api/projects/newproject HTTP/1.1
Content-Type: multipart/form-data; boundary=XXX
User-Agent: PostmanRuntime/7.29.0
Accept: */*
Postman-Token: a339b8c1-caa3-4629-8adf-d20967f84
Host: my-projectxxx.cloudfunctions.net
Accept-Encoding: gzip, deflate, br
Connection: keep-alive
Cookie: connect.sid=s%3A3h93yTISWRf4cibUG-8Ra3HpqV_iznVz.GhVvgAynx1RuwTyzjCCAlb%2FspGgTzf%2F%2F6VJrkGvNJ
Content-Length: 718115
 
--XXX
Content-Disposition: form-data; name="file"; filename="aliens.png"
Content-Type: image/png
<aliens.png>
--XXX
Content-Disposition: form-data; name="name"
Content-Type: text
John
--XXX
Content-Disposition: form-data; name="is_photo_changed"
Content-Type: text
1
--XXX--
 
HTTP/1.1 500 Internal Server Error
access-control-allow-credentials: true
access-control-allow-origin: http://localhost:3000
content-security-policy: default-src 'none'

下面是我的API后端日志中记录的错误:

Unexpected end of form at Multipart._final (/workspace/node_modules/busboy/lib/types/multipart.js:588:17) at callFinal (node:internal/streams/writable:694:27) at prefinish (node:internal/streams/writable:723:7) at finishMaybe (node:internal/streams/writable:733:5) at Multipart.Writable.end (node:internal/streams/writable:631:5) at onend (node:internal/streams/readable:693:10) at processTicksAndRejections (node:internal/process/task_queues:78:11)

它可以在本地运行,但在谷歌云功能中部署和使用后会抛出一个错误。请求有问题吗?有没有 Postman 的替代方案要测试?

np8igboo

np8igboo1#

在我的情况下,这是由于在控制器函数之前使用了multer上载函数。将上载函数放置在控制器函数之后解决了这个错误。

router.post(
  "/",
  validateAccessToken,
  validateAdminRole,
  validateCreateBlogSchema,
  blogController.create,
  upload.single("image")
);
goqiplq2

goqiplq22#

标题和内容之间必须有一个空行,例如:

--XXX
Content-Disposition: form-data; name="name"
Content-Type: text

John
--XXX

多部分请求主体中的行必须以CRLF结尾,而不仅仅是LF。
下面的代码演示了这一点:

express().post("/", multer().fields([]), function(req, res) {
  res.json(req.body);
})
.listen(80, function() {
  http.request("http://localhost", {
    method: "POST",
    headers: {"Content-Type": "multipart/form-data;boundary=XXX"}
  }).end(`--XXX
Content-Disposition: form-data; name="name"
Content-Type: text

John
--XXX--`.replace(/\n/g,"\r\n"))
  .on("response", function(r) {
    r.pipe(process.stdout);
  });
});

删除John之前的空行或删除.replace会导致multer中出现"Unexpected end of form"错误。

相关问题